翻譯:BioIT 愛好者
原文:TypeError: A Bytes-Like object Is Required, not 'str' | Finxter
簡介
目標:在本教程中,我們的目標是修復以下的 TypeError: A Bytes-Like object Is Required, not 'str'
異常,並且還討論了類似的異常及其解決方案。
示例:考慮以下文件 'scores.txt',其中包含一些隨機候選者的分數。
https://blog.finxter.com/wp-content/uploads/2021/04/scores.txt
Mike - 80
Boby - 60
Joe - 75
Shaw - 85
Ravi - 65

with open("scores.txt","rb") as p:
lines = p.readlines()
for line in lines:
string=line.split('-')
if 'Ravi' in string[0]:
print('Marks obtained by Ravi:',string[1].strip())
輸出:
Traceback (most recent call last):
File "main.py", line 4, in <module>
string=line.split('-')
TypeError: a bytes-like object is required, not 'str'
解析:
如您所見,我們遇到了一個 TypeError 異常:TypeError: a bytes-like object is required, not 'str',因為我們試圖使用 'str' 類型的分隔符分割一個 'bytes' 對象。
因此,要解決我們的問題,首先讓我們了解什么是 TypeError?
Python 中的 TypeError 是什么?
TypeError 是 Python 程序員最常面臨的問題之一。
每當您在程序中使用不正確或不受支持的對象類型時,都會引發該錯誤。
如果嘗試調用不可調用的對象或通過非迭代標識符進行迭代,也會引發此錯誤。例如,如果您嘗試使用 "str" 添加 "int" 對象。
a = 1
b = 2
c = 'Three'
print(a + b + c) # Trying to add 'int' objects with 'str'
輸出:
Traceback (most recent call last):
File "main.py", line 4, in <module>
print(a + b + c) # Trying to add 'int' objects with 'str'
TypeError: unsupported operand type(s) for +: 'int' and 'str'
解決:
要解決上述問題,可以為變量 c 提供一個 'int' 對象,也可以將變量 a 和 b 的類型轉換為 'str' 類型。
TypeError: A Bytes-Like object Is Required, not 'str' 是什么?

當你嘗試在僅支持 'bytes' 對象的操作中使用 'str' 對象時,就會引發 TypeError: A Bytes-Like object Is Required, not 'str' 的異常。
因此,你可以看到在上述從 'scores.txt' 中提取數據的示例時,我們嘗試使用 'str' 拆分字節對象,這是不受支持的操作。因此,Python 引發 TypeError。
如何修復 TypeError: A Bytes-Like object Is Required, not 'str'?

有許多解決上述異常的方法。您可以使用選擇似乎更適合您的程序的方式。讓我們一一介紹。
方案1:將 "rb' 替換為 "rt"
你可以簡單地將模式從 "rb"(即只讀二進制)更改為 "rt"(即只讀文本)。你甚至可以使用 'r' 表示只讀模式,這是 open() 的默認模式。with open("scores.txt", "rt") as p: # using rt instead of rb
lines = p.readlines()
for line in lines:
string = line.split('-')
if 'Ravi' in string[0]:
print('Marks obtained by Ravi:', string[1].strip())
輸出:
Marks obtained by Ravi: 65
因此,以文本模式打開文件后,你不再需要處理字節對象並輕松使用字符串。
方案2:添加前綴 "b"
你可以在split()
方法中的分隔符之前簡單地添加前綴 "b"。此前綴確保您可以處理字節對象。
with open("scores.txt", "rb") as p: # using prefix b
lines = p.readlines()
for line in lines:
string = line.split(b'-')
if b'Ravi' in string[0]:
print('Marks obtained by Ravi:', string[1].strip())
輸出:
Marks obtained by Ravi: b'65'
方案3:使用 decode() 方法
decode() 是一種編碼方案轉換的 Python 方法,在該方案中,將參數字符串編碼為另一種所需的編碼方案。默認情況下,當未提供編碼參數時,decode() 方法會將編碼方案設為 "utf-8"。
因此,您可以使用 decode() 方法將 'bytes' 類型的對象解碼或轉換為 'str' 類型。with open("scores.txt", "rb") as p:
lines = [x.decode() for x in p.readlines()] # applying decode()
for line in lines:
string = line.split('-') # no exception raised because line is of 'str' type
if 'Ravi' in string[0]:
print('Marks obtained by Ravi:', string[1].strip())
輸出:
Marks obtained by Ravi: 65
方案4:使用 encode() 方法
就像 decode() 方法一樣,我們可以使用 encode() 方法來解決相同的問題。with open("scores.txt", "rb") as p:
lines = p.readlines()
for line in lines:
string = line.split('-'.encode()) # encode converts ‘str’ to ‘bytes’
if 'Ravi'.encode() in string[0]:
print('Marks obtained by Ravi:', string[1].strip())
輸出:
Marks obtained by Ravi: b'65'
方案5:使用 bytes() 方法
bytes() 是 Python 中的一種方法,可用於將給定的字符串轉換為 'bytes' 類型。你需要提供將要轉換的源字符串,並將編碼(在這種情況下為 "utf-8")作為方法的參數。
讓我們應用 bytes() 方法解決我們的問題。with open("scores.txt", "rb") as p:
lines = p.readlines()
for line in lines:
string = line.split(bytes('-', 'utf-8')) # converts str to bytes
if bytes('Ravi', 'utf-8') in string[0]:
print('Marks obtained by Ravi:', string[1].strip())
輸出:
Marks obtained by Ravi: b'65'
注意:UTF-8 是用於編碼 Unicode 字符的字節編碼。
方案6:使用 List Comprehension 和 str() 方法
解決我們問題的另一種方法是在 list comprehension 中使用 str() 方法。這使您可以將 bytes 對象轉換為 str 類型。with open("scores.txt", "rb") as p:
lines = [str(x) for x in p.readlines()] # using str() to typecast bytes to str
for line in lines:
my_string = line.split('-')
if 'Ravi' in my_string[0]:
print('Marks obtained by Ravi:', my_string[1].strip(" '"))
輸出:
Marks obtained by Ravi: 65
總結
現在讓我們回顧一下本教程中討論的關鍵點:
Python 中的 TypeError 是什么?
TypeError: A Bytes-Like object Is Required, not 'str' 是什么?
如何修復 TypeError: A Bytes-Like object Is Required, not 'str'?
請訂閱並繼續關注,以便將來進行更多有趣的討論。
Happy coding! 😃

如何卸載 python setup.py install 安裝的包?




本文分享自微信公眾號 - 生信科技愛好者(bioitee)。
如有侵權,請聯系 support@oschina.cn 刪除。
本文參與“OSC源創計划”,歡迎正在閱讀的你也加入,一起分享。