我正在嘗試讀取和處理文件。這在Python2.7中完全正常,但我無法在Python 3中工作。 在Python 2.7中,它無需任何編碼就可以工作,而在Python 3中,我嘗試了使用和不使用編碼的所有組合。將字節轉換爲python 3.6中的字符串
深潛後,我發現read
返回的內容在兩個版本中都有所不同。在Python 2.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
我想獲得相同的輸出在Python 2.7。該content
應string
型和content[0]
應str的'\x04'
而不是int 4
我如何能得到這個任何指針?我嘗試過沒有任何成功的編碼。
您是否嘗試過'content.decode( 'unicode_escape')'? –
'content [:1]'怎麼樣?那會給你'b'\ x04''。 –
@SamChats的解決方案適用於我。 – nCessity