utf 8 - Write to utf-8 file in python - Stack Overflow

Disclaimer: I'm not a Python programmer.

I believe the problem is that codecs.BOM_UTF8 is a byte string, not a Unicode string. I suspect the file handler is trying to guess what you really mean based on "I'm meant to be writing Unicode as UTF-8-encoded text, but you've given me a byte string!"

Try writing the Unicode string for the byte order mark (i.e. Unicode U+FEFF) directly, so that the file just encodes that as UTF-8:

import codecs

file = codecs.open("lol", "w", "utf-8")
file.write(u'\ufeff')
file.close()

(That seems to give the right answer - a file with bytes EF BB BF.)

EDIT: S. Lott's suggestion of using "utf-8-sig" as the encoding is a better one than explicitly writing the BOM yourself, but I'll leave this answer here as it explains what was going wrong before.

相关文章:

  • 2021-12-01
  • 2022-12-23
  • 2021-04-07
  • 2022-12-23
  • 2022-12-23
  • 2021-07-11
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-12-12
  • 2021-04-26
  • 2021-11-26
  • 2022-12-23
  • 2021-07-15
相关资源
相似解决方案