[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
β.
- For example, if you try to add an β
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
- 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!