问题:
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