python unicode : when written to file, 以不同的格式写入

标签 python python-3.x unicode utf-8 mojibake

我正在使用 Python 3.4 将 unicode 字符串写入文件。 文件写入后,打开一看,完全是另外一组字符。

代码:-

# -*- coding: utf-8 -*-

with open('test.txt', 'w', encoding='utf-8') as f:
    name = 'أبيض'
    name.encode("utf-8")
    f.write(name)
    f.close()    

f = open('test.txt','r')
for line in f.readlines():
    print(line) 

输出:-

أبيض

提前致谢

最佳答案

您还需要指定在阅读 时使用的编解码器:

f = open('test.txt','r', encoding='utf8')
for line in f.readlines():
    print(line) 

否则将使用您的系统默认设置;查看open() function documentation :

encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever locale.getpreferredencoding() returns), but any encoding supported by Python can be used.

根据您获得的输出判断,您的系统正在使用 Windows Codepage 1252作为默认值:

>>> 'أبيض'.encode('utf8').decode('cp1252')
'أبيض'

通过在阅读时使用错误的编解码器,您创建了所谓的 Mojibake .

请注意,您编写示例中的 name.encode('utf8') 行完全是多余的;该调用的返回值被忽略,f.write(name) 调用负责实际编码。 f.close() 调用也是完全多余的,因为 with 语句已经负责关闭您的文件。以下将产生正确的输出:

with open('test.txt', 'w', encoding='utf-8') as f:
    name = 'أبيض'
    f.write(name)

with open('test.txt', 'r', encoding='utf-8') as f:
    for line in f.readlines():
        print(line) 

关于python unicode : when written to file, 以不同的格式写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32413002/

相关文章:

Java 字符串转unicode

python - Centos6.9安装python3.5 make后显示error permission denied

python-3.x - 无法对 dict_keys/dict_values/dict_items 进行 "type is"测试?

python - 字典类未初始化

python - 如何使用 BeautifulSoup 获取最后一个 URL 链接元素

python - 使用 Beautiful Soup 查找包含 unicode 字形的元素

python - 在 Python 中覆盖/更改 CSV 上的字段

python - 如何在 ironpython 2.7.5 中支持 numpy、scipy

python - 服从测试山羊 - 回溯

java - 在 Java 中打印 Unicode