我有用UTF16 LE BOM编码编码的文件,需要修改和保存它们。但是,我在https://docs.python.org/3.10/library/codecs.html#standard-encodings中看不到这样的编码选项。
我的代码:
with open("file.txt", mode='w', encoding="utf_16_le") as file:
content = file.read()
function_to_replace_content(content)
file.write(content)
这将保存没有BOM的文件。是否有选项可以对文件进行编码,包括BOM并以这种方式保存它?
这里类似的问题没有很好的解释和/或有效的答案。
发布于 2022-04-08 14:06:20
好吧,我很快就知道了:
# 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)
https://stackoverflow.com/questions/71798023
复制相似问题