翻译:BioIT 爱好者 原文:TypeError: A Bytes-Like object Is Required, not 'str' | Finxter
目标:在本教程中,我们的目标是修复以下的 TypeError: A Bytes-Like object Is Required, not 'str'
异常,并且还讨论了类似的异常及其解决方案。
示例:考虑以下文件 'scores.txt',其中包含一些随机候选者的分数。
Mike - 80
Boby - 60
Joe - 75
Shaw - 85
Ravi - 65
现在,让我们尝试在一个简单程序的帮助下从文件中获得 Ravi 的分数。
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?
TypeError 是 Python 程序员最常面临的问题之一。
示例:
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'?
有许多解决上述异常的方法。您可以使用选择似乎更适合您的程序的方式。让我们一一介绍。
你可以简单地将模式从 "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
因此,以文本模式打开文件后,你不再需要处理字节对象并轻松使用字符串。
你可以在 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'
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
就像 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'
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 字符的字节编码。
解决我们问题的另一种方法是在 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
现在让我们回顾一下本教程中讨论的关键点:
请订阅并继续关注,以便将来进行更多有趣的讨论。
Happy coding! 😃