python很容易将unicode写入文件?

2024-06-25 23:00:22 发布

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

我想确保代码中的所有字符串都是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("中文")

如果我只想写入文件,我仍然认为这太多了,还有更简单的方法吗?


Tags: 字符串fromtestimportaswithunicodefuture
2条回答

不需要调用.encode(),也不需要显式调用locale.getdefaultlocale()

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import io

with io.open('/tmp/test', 'w') as file:
    file.write(u"中文" * 4)

它使用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代码是:

#!/usr/bin/env python3

with open('/tmp/test', 'w') as file:
    file.write("中文" * 4)

这个解决方案怎么样?

Write to UTF-8 file in Python

只有三行代码。

相关问题 更多 >