utf 8 - Write to utf-8 file in python - Stack Overflow
2012-09-25 15:32
633 查看
utf 8 - Write to utf-8 file in python - Stack Overflow
Disclaimer: I'm not a Python programmer.
I believe the problem is that
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:
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.
I believe the problem is that
codecs.BOM_UTF8is 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.
相关文章推荐
- utf 8 - Write to utf-8 file in python - Stack Overflow
- How can I force Python's file.write() to use the same newline format in Windows as in Linux (“\r\n”
- Python: Write UTF-8 characters to csv file
- How to write a UTF-8 file with Java? - Stack Overflow
- how to write super fast file streaming code in C#?
- A good blog about how to write an Hadoop MapReduce program in Python
- prjGetWriteINIFile - How to Read-Write INI file using VB & API - 读取/写入INI文件 - VB6 + API - SourceCode - HackerJLY
- How to use UTF-8 in Python
- How to write UTF-8 encoded data into a file – Java
- Convert SVG to PNG in Python - Stack Overflow
- how to write a DLL/SO in C/C++ for Python
- Python学习笔记:Convert UTF-8 with BOM to UTF-8 without BOM in Python
- python use dom to write xml file
- nginx编译安装报错src/os/unix/ngx_files.c: In function 鈔gx_write_chain_to_file?
- recursion - How to write a simple preorder DOM tree traversal algorithm in jQuery? - Stack Overflow
- vim - How to jump back to NERDTree from file in tab? - Stack Overflow
- Python学习笔记:Convert UTF-8 with BOM to UTF-8 without BOM in Python
- Python load json file with UTF-8 BOM header - Stack Overflow
- How to convert `ctime` to `datetime` in Python? - Stack Overflow
- How to properly use relative or absolute imports in Python modules? - Stack Overflow