我想确保代码中的所有字符串都是unicode,所以我使用unicode_literals
,然后需要将字符串写入文件:
from __future__ import unicode_literals
with open('/tmp/test', 'wb') as f:
f.write("中文") # UnicodeEncodeError
所以我需要这样做:
from __future__ import unicode_literals
with open('/tmp/test', 'wb') as f:
f.write("中文".encode("utf-8"))
f.write("中文".encode("utf-8"))
f.write("中文".encode("utf-8"))
f.write("中文".encode("utf-8"))
但每次我需要编码时,我都很懒,所以我改为编解码器:
from __future__ import unicode_literals
from codecs import open
import locale, codecs
lang, encoding = locale.getdefaultlocale()
with open('/tmp/test', 'wb', encoding) as f:
f.write("中文")
如果我只想写入文件,我仍然认为这太多了,还有更简单的方法吗?
不需要调用
.encode()
,也不需要显式调用locale.getdefaultlocale()
:它使用
locale.getpreferredencoding(False)
字符编码将Unicode文本保存到文件中。在Python 3上:
不需要使用显式编码声明(
# -*- coding: utf-8 -*-
),就可以在Python源代码中使用文字非ascii字符。utf-8
是默认值。你不需要使用
import io
:内置的open()
就在那里io.open()
u''
(u
前缀)。''
默认情况下,文本为Unicode。如果您想省略u''
,那么将from __future__ import unicode_literals
放回问题代码中。也就是说,完整的Python 3代码是:
这个解决方案怎么样?
Write to UTF-8 file in Python
只有三行代码。
相关问题 更多 >
编程相关推荐