Write 'text' to file ('filename') assuming 'encoding' in an atomic way
    Return (eventually new) encoding

def write(text, filename, encoding='utf-8', mode='wb'):
    """
    Write 'text' to file ('filename') assuming 'encoding' in an atomic way
    Return (eventually new) encoding
    """
    text, encoding = encode(text, encoding)
    if 'a' in mode:
        with open(filename, mode) as textfile:
            textfile.write(text)
    else:
        with atomic_write(filename,
                          overwrite=True,
                          mode=mode) as textfile:
            textfile.write(text)
    return encoding