import gzip
import bz2


def open_by_suffix(file_name, mode='r'):
    """Opens file based on suffix."""

    # noqa modified from https://stackoverflow.com/questions/18367511/how-do-i-automatically-handle-decompression-when-reading-a-file-in-python
    file_name = str(file_name)

    if file_name.endswith('gz'):
        handle = gzip.open(filename=file_name, mode=mode + 't')
    elif file_name.endswith('bz2'):
        handle = bz2.open(filename=file_name, mode=mode + 't')
    else:
        handle = open(file=file_name, mode=mode)

    return handle