2017-06-25 33 views
0

我在我的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() 

`

+0

没有任何代码来看看,你的问题很难回答。如果在打开文件时使用'encoding'参数,您的问题很可能会消失。 –

+0

我,我要更新我的问题谢谢你的回答,但没有按照我的方法来运用你的帮助,或许还有其他的方法。 –

回答

1

为Python 3.你应该写的str到文件为bytes使用str.encode(),然后打开该文件作为写入二进制模式open('filename.txt', 'wb')。在读取时,将文件读取为读取二进制模式。 open('filename.txt', 'rb')并使用bytes.decode()将其转换回str

您可以使用此作为参考:

utfchar = '¶' 
with open('filename.txt', 'wb') as fp: 
    fp.write(utfchar.encode()) 

# and later: 

with open('filename.txt', 'rb') as fp: 
    utfchar = fp.read().decode() 

assert utfchar == '¶' 
+0

谢谢你工作得很好, –

0

在Python 3,你可以简单地写字符串:

+0

ok在这部分没有问题,我在加载和解码下一部分代码中的数据时遇到问题,谢谢你的回答。 –