在 Python 中写入 UTF-8 文件 - Write to UTF-8 file in Python

问题:

I'm really confused with the codecs.open function .我真的对codecs.open function感到困惑。 When I do:当我做:

file = codecs.open("temp", "w", "utf-8")
file.write(codecs.BOM_UTF8)
file.close()

It gives me the error它给了我错误

UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128) UnicodeDecodeError: 'ascii' 编解码器无法解码位置 0 中的字节 0xef: 序号不在范围内 (128)

If I do:如果我做:

file = open("temp", "w")
file.write(codecs.BOM_UTF8)
file.close()

It works fine.它工作正常。

Question is why does the first method fail?问题是为什么第一种方法会失败? And how do I insert the bom?以及如何插入 bom?

If the second method is the correct way of doing it, what the point of using codecs.open(filename, "w", "utf-8") ?如果第二种方法是正确的方法,那么使用codecs.open(filename, "w", "utf-8")什么意义?


解决方案:

参考一: https://stackoom.com/question/3v16
参考二: Write to UTF-8 file in Python
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章