Do I have to encode unicode variable before write to file?

时光总嘲笑我的痴心妄想 提交于 2019-12-11 09:05:47

问题


I read the "Unicdoe Pain" article days ago. And I keep the "Unicode Sandwich" in mind.

Now I have to handle some Chinese and I've got a list

chinese = [u'中文', u'你好']

Do i need to proceed encoding before writing to file?

add_line_break = [word + u'\n' for word in chinese]
encoded_chinese = [word.encode('utf-8') for word in add_line_break]
with open('filename', 'wb') as f:
    f.writelines(encoded_chinese)

Somehow I find out that in python2. I can do this:

chinese = ['中文', '你好']
with open('filename', 'wb') as f:
    f.writelines(chinese)

no unicode matter involed. :D


回答1:


You don't have to do that, you could use io or codecs to open the file with encoding.

import io
with io.open('file.txt', 'w', encoding='utf-8') as f:
    f.write(u'你好')

codecs.open has the same syntax.




回答2:


In python3;

with open('file.txt, 'w', encoding='utf-8') as f:
    f.write('你好')

will do just fine.



来源:https://stackoverflow.com/questions/45726305/do-i-have-to-encode-unicode-variable-before-write-to-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!