簡體   English   中英

UnicodeDecodeError:“ ascii”編解碼器無法解碼字節0xe4

[英]UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4

我想知道是否有人可以幫助我,我已經嘗試過事先搜索,但找不到答案:

我有一個名為info.dat的文件,其中包含:

#
# *** Please be aware that the revision numbers on the control lines may not always
# *** be 1 more than the last file you received. There may have been additional
# *** increments in between.
#
$001,427,2018,04,26
#
# Save this file as info.dat
#

我正在嘗試循環文件,獲取版本號並將其寫入其自己的文件

with open('info.dat', 'r') as file:
    for line in file:
        if line.startswith('$001,'):
            with open('version.txt', 'w') as w:
                version = line[5:8] # Should be 427
                w.write(version + '\n')
                w.close()

盡管這確實寫入了正確的信息,但我不斷收到以下錯誤:

Traceback (most recent call last):
File "~/Desktop/backup/test.py", line 4, in <module>
for line in file:
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 6281: ordinal not in range(128)

嘗試添加以下內容時

with open('info.dat', 'r') as file:
    for line in file:
        if line.startswith('$001,'):
            with open('version.txt', 'w') as w:
                version = line[5:8]
                # w.write(version.encode('utf-8') + '\n')
                w.write(version.decode() + '\n')
                w.close()

我收到以下錯誤

Traceback (most recent call last):
File "~/Desktop/backup/test.py", line 9, in <module>
w.write(version.encode('utf-8') + '\n')
TypeError: can't concat str to bytes

您正在嘗試打開一個文本文件,該文件將使用默認編碼對每行進行隱式解碼,然后使用UTF-8手動對每行進行重新編碼,然后將其寫入文本文件,這將對UTF-8進行隱式解碼再次使用您的默認編碼。 那是行不通的。 但好消息是, 正確的做法要簡單得多。


如果您知道輸入文件為UTF-8(可能不是,請參見下文),則只需以UTF-8而不是默認編碼打開文件即可:

with open('info.dat', 'r', encoding='utf-8') as file:
    for line in file:
        if line.startswith('$001,'):
            with open('version.txt', 'w', encoding='utf-8') as w:
                version = line[5:8] # Should be 427
                w.write(version + '\n')
                w.close()

實際上,我非常確定您的文件不是 UTF-8,而是Latin-1(在Latin-1中, \\xa3ä ;在UTF-8中,這是一個3字節序列的開始,該序列可能會編碼一個CJK字符)。 如果是這樣,您可以使用正確的編碼而不是錯誤的編碼執行相同的操作,現在它可以工作。


但是,如果您不知道編碼是什么,請不要猜測。 只是堅持使用二進制模式。 這意味着傳遞rbwb模式而不是rw ,並使用bytes常量:

with open('info.dat', 'rb') as file:
    for line in file:
        if line.startswith(b'$001,'):
            with open('version.txt', 'wb') as w:
                version = line[5:8] # Should be 427
                w.write(version + b'\n')
                w.close()

無論哪種方式,都無需在任何地方調用encodedecode 只需讓文件對象為您處理,並在任何地方都只處理一種類型(無論是str還是bytes )。

encode()返回字節,但“ \\ n”是字符串,您需要將字符串形式的字節轉換為字節+字節,因此請嘗試此操作

w.write(version.encode('utf-8') + b'\n')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM