python写unicode容易文件?

rog*_*ger 5 python unicode file

我想确保我的代码中的所有字符串都是unicode,所以我使用unicode_literals,然后我需要将字符串写入文件:

from __future__ import unicode_literals
with open('/tmp/test', 'wb') as f:
    f.write("??") # UnicodeEncodeError
Run Code Online (Sandbox Code Playgroud)

所以我需要这样做:

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"))
Run Code Online (Sandbox Code Playgroud)

但每次我需要在代码中编码时,我都很懒,所以我改为编解码器:

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("??")
Run Code Online (Sandbox Code Playgroud)

如果我只想写文件,任何更简单的方法,我还是认为这太过分了?

Dou*_*ser 0

这个解决方案怎么样?

在Python中写入UTF-8文件

只有三行代码。