加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python写unicode容易文件?

发布时间:2020-12-16 22:51:36 所属栏目:Python 来源:网络整理
导读:我想确保我的代码中的所有字符串都是unicode,所以我使用unicode_literals,然后我需要将字符串写入文件: from __future__ import unicode_literalswith open('/tmp/test','wb') as f: f.write("中文") # UnicodeEncodeError 所以我需要这样做: from __futur

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

#!/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:builtin open()就是io.open()
>您不需要使用u”(u前缀). ”默认情况下,文字是Unicode.如果你想省略你”然后从__future__中恢复导入unicode_literals,就像问题中的代码一样.

即,完整的Python 3代码是:

#!/usr/bin/env python3

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读