Skip to content Skip to sidebar Skip to footer

Do I Have To Encode Unicode Variable Before Write To File?

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

Solution 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.

Solution 2:

In python3;

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

will do just fine.

Post a Comment for "Do I Have To Encode Unicode Variable Before Write To File?"