gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:06:08 26 4
gpt4 key购买 nike

我正在使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com