我正在尝试读取和处理一个文件。这在Python2.7中运行得非常好,但我无法在Python 3中运行它。 在Python2.7中,它在不提供任何编码的情况下工作,而在Python3中,我尝试了有编码和无编码的所有组合。
经过深入研究,我发现read
返回的内容在两个版本中是不同的。
在Python2.7中工作的代码:
>>> f = open('resource.cgn', 'r')
>>> content = f.read()
>>> type(content)
<type 'str'>
>>> content[0:20]
'\x04#lwq \x7f`g \xa0\x03\xa3,ess to'
>>> content[0]
'\x04'
但是在Python 3中:
>>> f = open('resource.cgn','r')
>>> content = f.read()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python3.6/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec cant decode byte 0xa0 in position 10: ordinal not in range(128)
>>> f = open('resource.cgn','rb')
>>> content = f.read()
>>> type(content)
<class 'bytes'>
>>> content[0:20]
b'\x04#lwq \x7f`g \xa0\x03\xa3,ess to'
>>> content[0]
4
>>> content.decode('utf8')
Traceback (most recent call last):
File "<console>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 10:
invalid start byte
我希望得到与Python2.7中相同的输出。content
应该是string
类型,content[0]
应该是str'\x04'
,而不是int4
有什么线索可以告诉我怎么得到这个吗?我试过编码,但没有成功。
默认情况下,3.X的}现在是3.X中的
str
现在是2.X的unicode
,在3.X中以文本模式打开的文件对象分别在读取或写入文件时尝试解码和编码。^2.X的{bytes
。3.Xbytes
和2.X的str
之间确实有非常小的差别,两者基本上都包含8位文本。下面是在3.X中将
b'\x04#lwq \x7f`g \xa0\x03\xa3,ess to'
转换为str
的一个简单技巧:解码
bytes
字符串失败,因为您有无效的UTF-8字符字节,与ASCII相同。但是,明智的做法是,
bytes
用于处理二进制数据,而str
仅用于3.X中的Unicode字符串。建议使用bytes
,而不是str
用于3.X中的二进制字符串:相关问题 更多 >
编程相关推荐