我可以使用Python 3编码字符串,将其保存到文件中,读回并解码吗?

是否可以使用带有重音符号的字符串,将其存储在本地文件中,从该文件中读取,然后将其恢复为原始格式?

我一直在尝试使用utf-8对字符串进行编码。 write()方法仅接受str参数。 encode()方法仅接受字节参数。除非对数据进行编码,否则无法写入文件,但是无法还原。

这是我要运行的代码:

unicode = "utf-8"
name = "Dončić"
with open("doncic",'w') as file:
    file.write(str(name.encode(unicode)))

with open("doncic",'r',encoding='utf8') as file:
print(file.read())

我一直在寻找答案几个小时,而我发现的解决方案都没有包含任何文件I / O。

这是我的第一篇文章!谢谢您的帮助!

vcaonimav 回答:我可以使用Python 3编码字符串,将其保存到文件中,读回并解码吗?

Python可以以两种模式(文本或二进制)打开文件。 文本模式可以为您处理编码,您可以直接读写字符串,包括所有非ASCII字符。

文本模式,由python处理的编码:

with open('text.txt','w',encoding='utf-8') as f:
    f.write('Hellø Wőrld')

# read back
with open('text.txt',encoding='utf-8') as f:
    print(f.read())

二进制模式,由您处理的编码:

with open('text.txt','wb') as f:
    f.write('Hellø Wőrld'.encode('utf-8'))

# read back
with open('text.txt','rb') as f:
    print(f.read().decode('utf-8'))
,

一种选择是存储和读取 binary

unicode = "utf-8"
name = "Dončić"
with open("doncic",'wb') as file:
    file.write(name.encode(unicode))

with open("doncic",'rb') as file:
    print(file.read().decode(unicode))

第二个(可能更简单)的选择是使用open encoding 参数。

unicode = "utf-8"
name = "Dončić"
with open('text.txt',encoding=unicode) as file:
    file.write(name)

with open('text.txt','r',encoding=unicode) as file:
    print(file.read())

第三个选择是,如果您的默认或首选编码已经是utf-8,则忽略编码。

import locale

unicode = "utf-8"
name = "Dončić"

assert locale.getpreferredencoding().upper() == 'UTF-8'

with open('text.txt','w') as file:
    file.write(name)

with open('text.txt','r') as file:
    print(file.read())

很明显,断言可能是也可能不是在程序中验证这一点的好选择。但这指出它可以立即使用。

我使用Python 3.7运行了所有代码片段。

所有情况下的输出为:

  

Dončić

,

编码一个字符串,将文件打开为二进制格式,写一个字符串

以读取的二进制格式打开文件,然后解码字符串

否则以读取格式(“ r”而不是“ rb”)打开文件,它将为您解码字符串

str_original = 'Hello'


with open(filepath,'wb') as f:        
    f.write(str_original.encode(encoding='utf-8'))       


f = open(filepath,"rb")
print(f.read().decode())
f.close()
本文链接:https://www.f2er.com/3104858.html

大家都在问