import io
import gzip


def openOptGzipFile(filename, modes='r'):
    """
    openOptGzipFile(filename, modes='r') - Open file with optional gzip
    compression

    Args:
        filename:  The full path to a file
        modes   :  File open modes 'r', 'rw', or 'w'

    Returns:
        A file object
    """
    f = open(filename, 'b'+modes)
    # First two byte signature of a gzip'd file
    if (f.read(2) == b'\x1f\x8b'):
        f.seek(0)
        return io.TextIOWrapper(gzip.GzipFile(fileobj=f), encoding='utf-8')
    else:
        f.seek(0)
        return io.TextIOWrapper(f, encoding='utf-8')