在 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章