import hashlib
import io


def calc_file_md5(filepath, chunk_size=None):
    """
    Calculate a file's md5 checksum. Use the specified chunk_size for IO or the
    default 256KB

    :param filepath:
    :param chunk_size:
    :return:
    """
    if chunk_size is None:
        chunk_size = 256 * 1024
    md5sum = hashlib.md5()
    with io.open(filepath, 'r+b') as f:
        datachunk = f.read(chunk_size)
        while datachunk is not None and len(datachunk) > 0:
            md5sum.update(datachunk)
            datachunk = f.read(chunk_size)

    return md5sum.hexdigest()