import gzip


def opengz(file, mode="r"):
    """
    Transparently open a gzipped or non-gzipped file for reading or writing. 
    :param file: Path of file to open for writing.
    :param mode: Same mode options as python's default open.
    :return: A open file handle.
    """
    assert mode in ['r', 'rb', 'a', 'ab', 'w', 'wb']
    if mode == 'wb' or (mode == 'w' and file.endswith('.gz')):
        return gzip.open(file, 'wb')
    elif mode == 'ab' or (mode == 'a' and file.endswith('.gz')):
        return gzip.open(file, 'ab')
    elif mode == 'w':
        return open(file, 'w')
    f = open(file, 'rb')
    if f.read(2) == '\x1f\x8b':
        f.seek(0)
        return gzip.GzipFile(fileobj=f, mode=mode)
    else:
        f.close()
        return open(file, mode)