Python 中常见的 TypeError 是什么?

翻译: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
41dc7753-2a3d-4ac5-b352-1cbc3cdce743.png
现在,让我们尝试在一个简单程序的帮助下从文件中获得 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 4in <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 4in <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' 是什么?

e4ff656a-2c63-441e-968b-f7c5efbab584.png


当你尝试在仅支持 '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'?

e4ff656a-2c63-441e-968b-f7c5efbab584.png


有许多解决上述异常的方法。您可以使用选择似乎更适合您的程序的方式。让我们一一介绍。

方案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! 😃


545db418-e8ac-4980-9e5d-9a217ea26988.gif


Python 列表、字典、元组的一些小技巧

2021-03-30

79061489-3c44-49bc-a3d4-a1796138245b.jpg

如何卸载 python setup.py install 安装的包?

2020-05-15

ca176f0b-94ea-4a3e-bafb-60234699f832.jpg

生物信息学 Python 入门之源码安装

2019-09-29

9b960eee-a59c-450e-9dd3-0b62c414fe08.jpg

Python 日期和时间函数使用指南

2019-09-21

3c9e30b4-33d9-426c-93c3-2516c53b9d16.jpg

Python 文件与目录操作方法总结

2019-02-17

458fc6f3-5697-421c-a768-92f4c222952c.jpg


da3a9477-8bf0-4319-b061-5d70d400c8c4.png

本文分享自微信公众号 - 生信科技爱好者(bioitee)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

posted @ 2021-04-16 16:00  章鱼猫先生  阅读(1794)  评论(0编辑  收藏  举报