How to save txt file with UTF-16 LE BOM encoding in Python

1.1k views Asked by At

I have files encoded with UTF16 LE BOM encoding and need to alter them and save. However I could not see such encoding option in https://docs.python.org/3.10/library/codecs.html#standard-encodings

My code:

with open("file.txt", mode='w', encoding="utf_16_le") as file:
    content = file.read()
    function_to_replace_content(content)
    file.write(content)

This saves the file without BOM. Is there an option to encode the file including BOM and save it that way?

Similar questions here didn't have quite explanatory and/or working answers.

1

There are 1 answers

0
Mirek Hotový On

Alright, I got this pretty quick after all:

# Saves a file in fpath containing content using selected encoding
def save_file_contents(fpath, content, encoding, bom=None):
    with open(fpath, mode='w', encoding=encoding) as fout:
        if bom:
            fout.write(u'\ufeff')
        fout.write(content)
        print('Processed', fpath)

save_file_contents(fpath, content, 'utf-16-LE', bom=True)