在写入文件之前是否必须对unicode变量进行编码?

2024-05-15 22:15:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我几天前读过《独行侠之痛》的文章。我把“Unicode三明治”记在心里。 enter image description here

现在我要对付一些中国人,我有一张单子

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

写入文件前是否需要继续编码?你知道吗

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)

不知怎的,我在Python2中发现了。我可以做到:

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

不涉及任何问题。:D个


Tags: inaddforwritelinesaswithline文章
2条回答

Python3

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

会很好的。你知道吗

您不必这样做,您可以使用iocodecs以编码方式打开文件。你知道吗

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

codecs.open具有相同的语法。你知道吗

相关问题 更多 >