[Solved] TypeError: A Bytes-Like object Is Required, not β€˜str’

[toc]

Introduction

Objective: In this tutorial, our goal is to fix the following exception TypeError: A Bytes-Like object Is Required, not β€˜str’ and also discuss similar exceptions along with their solutions.

Example: Consider the following file β€˜scores.txt’which contains scores of some random candidates.

Now, let us try to access the score obtained by Ravi from the file with the help of a simple program.

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())

Output:

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    string=line.split('-')
TypeError: a bytes-like object is required, not 'str'

Explanation:

As you can see, we got an exception TypeError: a bytes-like object is required, not ‘str’ since we tried to split a β€˜bytes’ object using a separator of β€˜str’ type.

Thus to fix our problem, first of all let us understand what TypeError is?

? What is TypeError in Python?

TypeError is one of the most commonly faced problem by Python programmers.

  • It is raised whenever you use an incorrect or unsupported object type in a program.
  • It is also raised if you try to call a non-callable object or if you iterate through a non iterative identifier.
    • For example, if you try to add an β€˜int’ object with β€˜str’.

Example:

a = 1
b = 2
c = 'Three'
print(a + b + c)  # Trying to add 'int' objects with 'str'

Output:

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'

Solution: To fix the above problem, you can either provide an β€˜int’ object to variable c or you can typecast variable a and b to β€˜str’ type.

a = 1
b = 2
c = 3  # error fixed by using int object
print(a + b + c)

# Output: 6

Since we now have an idea about TypeErrors in Python, let us discuss – what is TypeError: A Bytes-Like object Is Required, not β€˜str’ ?

? What is TypeError: A Bytes-Like object Is Required, not β€˜str’ ?

TypeError: A Bytes-Like object Is Required, not β€˜str’ is raised when you try to use a β€˜str’ object in an operation which supports only β€˜bytes’ object.

Therefore when you have a look at the above example that involves extracting data from ‘scores.txt’, we are trying to use β€˜str’ to split a byte object which is an unsupported operation. Thus, Python raises the TypeError.

❖ How to Fix TypeError: a bytes-like object is required, not ‘str’ ?

There are numerous solutions to solve the above exception. You can use choose whichever seems more suitable for your program. Let’s dive into them one by one.

?️ Solution 1: Replacing β€˜rb’ with β€˜rt’

You can simply change the mode from β€˜rb’ i.e. read-only binary to β€˜rt’ i.e. read-only text. You can even use β€˜r’ that means read-only mode which is the default mode for 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())

Output:

Marks obtained by Ravi: 65

Thus, once the file is opened in text mode, you no longer have to deal with a byte object and easily work with strings.

?️ Solution 2: Adding prefix ‘b

You can simply add prefix β€˜b’ before the delimiter within the split() method. This prefix ensures that you can work upon a byte object.

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())

Output:

Marks obtained by Ravi: b'65'

?️ Solution 3: Using decode() Method

❖ decode() is a Python method that converts one encoding scheme, in which the argument string is encoded to another desired encoding scheme. The decode() method by default takes the encoding scheme as β€˜utf-8’ when no encoding arguments are given.

Thus, you can use the decode() method to decode or convert an object of  β€˜bytes’ type to β€˜str’ type.

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())

Output:

Marks obtained by Ravi: 65

?️ Solution 4: Using encode() Method

Just like the decode() method, we can use the encode() method for fixing the same problem.

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())

Output:

Marks obtained by Ravi: b'65'

Recommended Article: Python Unicode Encode Error

?️ Solution 5: Using bytes() Method

bytes() is a method in Python, that can be used to convert a given string to β€˜bytes’ type. You need to provide the string to be converted as source and the encoding which in this case is β€˜utf-8’ as arguments to the method.

Let’s apply the bytes() method to solve our problem.

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())

Output:

Marks obtained by Ravi: b'65'

❖ Note: UTF-8 is a byte encoding used to encode Unicode characters.

?️ Solution 6: Using a List Comprehension and str() Method

Another workaround to solve our problem is to be use the str() method within a list comprehension. This allows you to typecast the bytes object to str type.

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(" '"))

Output:

Marks obtained by Ravi: 65

Conclusion

Let us now recall the key points discussed in this tutorial:

  • What is TypeError in Python?
  • What is TypeError: A Bytes-Like object Is Required, not β€˜str’ ?
  • How to fix TypeError: a bytes-like object is required, not ‘str’ ?

Please subscribe and stay tuned for more interesting discussions in the future. Happy coding! ?

Authors:
?‍?
Shubham Sayon
?‍?
Anirban Chatterjee

The Complete Guide to PyCharm
  • Do you want to master the most popular Python IDE fast?
  • This course will take you from beginner to expert in PyCharm in ~90 minutes.
  • For any software developer, it is crucial to master the IDE well, to write, test and debug high-quality code with little effort.

Join the PyCharm Masterclass now, and master PyCharm by tomorrow!