'How to save txt file with UTF-16 LE BOM encoding in Python
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.
Solution 1:[1]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mark Tolonen |
