我在我的Python脚本中有一些非ASCII数据。 python可以正确处理它们,但是当我想保存它们时会出错。所以我用str.encode()
对它们进行编码,然后将它们写入文件。 读取文件和解码数据我没有问题在python 2.7中使用str.decode()
- 读取文件的数据是字符串 - 但在python 3.6中没有任何str.decode()
函数,我得到了问题。如何在python中读写utf_8?
即使在整个python官方文档中,我都找不到答案。
示例代码:忽略的情况下,请即时在thistime用手机写
string="hello=سلام -in persian"
file=open("file.txt",'w+', encoding='utf-8')
file.write(string.encode())
# using file.write(string) raises an error
print(file.read())# if the whole string be in Persian prints sth like b'\xff\xa3....'
file.read().decode()# raises an error contains: str object doesn'have attribute decode
# here was my problem in updating from 2.7 to 3.6
file.close()
`
没有任何代码来看看,你的问题很难回答。如果在打开文件时使用'encoding'参数,您的问题很可能会消失。 –
我,我要更新我的问题谢谢你的回答,但没有按照我的方法来运用你的帮助,或许还有其他的方法。 –