是否可以使用带重音符号的字符串,将其存储在本地文件中,从该文件中读取,然后将其恢复为原始格式?
我一直在尝试使用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。
这是我的第一篇文章!谢谢您的帮助!
将字符串编码为打开文件,然后以二进制格式写入字符串
以读取的二进制格式打开文件,然后解码字符串
否则以读取格式('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()
Python可以将文件打开为模式,文本或二进制。文本模式为您处理编码,您可以直接读写字符串,包括所有的nom-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))
输出为:Dončić