Do I have to encode unicode variable before write

2019-07-24 16:19发布

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

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

2条回答
甜甜的少女心
2楼-- · 2019-07-24 16:46

In python3;

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

will do just fine.

查看更多
放荡不羁爱自由
3楼-- · 2019-07-24 16:48

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.

查看更多
登录 后发表回答