python写unicode容易文件?

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

相关文章

使用OpenCV实现视频去抖 整体步骤: 设置输入输出视频 寻找帧...
前言 对中文标题使用余弦相似度算法和编辑距离相似度分析进行...
前言 之前尝试写过一个爬虫,那时对网页请求还不够熟练,用的...
前言 本文使用Python实现了PCA算法,并使用ORL人脸数据集进行...
前言 使用opencv对图像进行操作,要求:(1)定位银行票据的...
天气预报API 功能 从中国天气网抓取数据返回1-7天的天气数据...