Posted by Marta on March 24, 2021 Viewed 81968 times

In this article, I will explain why you will encounter the Typeerror a bytes-like object is required not ‘str’ error, and a few different ways to fix it.
The TypeError exception indicates that the operation you are trying to execute is not supported or not meant to be. You will usually get this error when you pass arguments of the wrong type. More details about the TypeError exception.

Apart from TypeError there are more exceptions in python. Check out this article to learn the most frequent exceptions and how to avoid them.
In this case, the bytes-like object is required message indicates the operation is excepting a bytes type; however, the type received was something else. Let’s see some examples.
Case #1: Reading from a file
This error comes up quite often when you are reading text from a file. Suppose that we have the following file, named file_sample.txt, containing the text below:
product;stock;price bike;10;50 laptop;3;1000 microphone;5;40 book;3;9
The file contains a list of products. Each line has the product name, the current stock available, and the price. I wrote a small program that will read the file and check if there are bikes available. Here is the code:
with open('file_sample.txt', 'rb') as f:
lines = [x.strip() for x in f.readlines()]
bike_available = False
for line in lines:
tmp = line.strip().lower()
split_line = tmp.split(';')
if split_line[0]=='bike' and int(split_line[1])>0:
bike_available = True
print("Bikes Available? "+ str(bike_available))
And the output will be :
Traceback (most recent call last):
Error line 7, in <module>
splitted_line = tmp.split(';')
TypeError: a bytes-like object is required, not 'str'
Explanation
When I opened the file, I used this: with open('file_sample.txt', 'rb') . rb is saying to open the file in reading binary mode. Binary mode means the data is read in the form of bytes objects. Therefore if we look at line 7, I try to split a byte object using a string. That’s why the operation results in TypeError. How can I fix this?
Solution #1: Convert to a bytes object
To fix the error, the types used by the split() operation should match. The simplest solution is converting the delimiter to a byte object. I achieve that just by prefixing the string with a b
with open('file_sample.txt', 'rb') as f:
lines = [x.strip() for x in f.readlines()]
bike_available = False
for line in lines:
tmp = line.strip().lower()
split_line = tmp.split(b';') # Added the b prefix
if split_line[0]==b'bike' and int(split_line[1])>0:
bike_available = True
print("Bikes Available? "+ str(bike_available))
Output:
Note I also added the b prefix, or bytes conversion, to the condition if split_line[0]==b'bike', so the types also match, and the comparison is correct.
Solution #2: Open file in text mode
Another possible solution is opening the file in text mode. I can achieve this just by removing the b from the open() action. See the following code:
with open('file_sample.txt', 'r') as f:
lines = [x.strip() for x in f.readlines()]
bike_available = False
for line in lines:
tmp = line.strip().lower()
split_line = tmp.split(';')
if split_line[0]=='bike' and int(split_line[1])>0:
bike_available = True
print("Bikes Available? "+ str(bike_available))
Output:
Typeerror: a bytes-like object is required, not ‘str’ replace
You could also find this error when you are trying to use the .replace() method, and the types are not matching. Here is an example:
text_in_binary = b'Sky is blue.Roses are red' #Bytes object
replaced_text = text_in_binary.replace('red','blue')
print(replaced_text)
Output:
Traceback (most recent call last):
File line 17, in <module>
replaced_text = text_in_binary.replace('red','blue')
TypeError: a bytes-like object is required, not 'str'
Solution #1
You can avoid this problem by making sure the types are matching. Therefore one possible solution is converting the string passed into the .replace() function( line 2), as follows:
text_in_binary = b'Sky is blue.Roses are red' replaced_text = text_in_binary.replace(b'red',b'blue') print(replaced_text)
Output:
b'Sky is blue.Roses are blue'
Note the result is a bytes object
Solution #2
Another way to get the types to match is converting the byte object to a string using the .decode() function( line 1), which will decode any binary content to string.
text= b'Sky is blue.Roses are red'.decode('utf-8')
print(type(text))
replaced_text = text.replace('red','blue')
print(replaced_text)
Output:
<class 'str'> Sky is blue.Roses are blue
Please note you could also save a string in the variable text. I am using decode() because this article aims to illustrate how to manipulate bytes objects.
Typeerror: a bytes-like object is required, not ‘str’ socket
You will encounter this error when you are trying to send a string via socket. The reason is the socket.send() function expect any data to be converted to bytes. Here is a code snippet that will throw the typeerror:
import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('www.py4inf.com', 80))
mysock.send('GET http://www.py4inf.com/code/romeo.txt HTTP/1.0nn')
while True:
data = mysock.recv(512)
if ( len(data) < 1 ) :
break
print (data);
mysock.close()
Output:
Traceback (most recent call last):
File line 4, in <module>
mysock.send('GET http://www.py4inf.com/code/romeo.txt HTTP/1.0nn')
TypeError: a bytes-like object is required, not 'str'
To fix this, you will need to convert the http request inside the string (line 4) to bytes. There are two ways you can do this. Prefixing the string with b, which will convert the string to bytes:
mysock.send(b'GET http://www.py4inf.com/code/romeo.txt HTTP/1.0nn')
or using .encode() method to convert the string to bytes:
mysock.send('GET http://www.py4inf.com/code/romeo.txt HTTP/1.0nn'.encode())
The output will be the same in both cases:
b'HTTP/1.1 404 Not FoundrnServer: nginxrnDate: Tue, 14 Jul 2020 10:03:11 GMTrnContent-Type: text/htmlrnContent-Length: 146rnConnection: closernrn<html>rn<head><title>404 Not Found</title></head>rn<body>rn<center><h1>404 Not Found</h1></center>rn<hr><center>nginx</center>rn</body>rn</html>rn'
The server response indicates the file we requested doesn’t exist. However, the code created the socket, and the HTTP request hit the destination server. Therefore we can consider the error fixed
Encode and decode in python
This error is mainly caused by passing the wrong type to a function. Therefore if a function is expecting the bytes object, we should convert the argument first. You can do so using the b prefix or using the .encode() function.
Bytes to String – Decode
string_var = b'Hello'.decode('utf-8')
print(type(string_var))
Output:
String to Bytes – Encode
bytes_var = 'Hello'.encode() print(type(bytes_var))
Output:
Conclusion
To summarise, when you encounter this error, it is important to double-checking the types you are used and make sure the types match, and you are not passing a wrong type to a function. I hope this helps and thanks for reading, and supporting this blog. Happy Coding!
Recommended Articles




TypeErrors happen all of the time in Python. This type of error is raised when you try to apply a function to a value that does not support that function. For example, trying to iterate over a number raises a TypeError because you cannot iterate over a number.
In this guide, we’re going to talk about how to solve the “typeerror: a bytes-like object is required, not ‘str’” error. We’ll walk through what this error means and why it is raised. We’ll also go through a solution to help you overcome this error. Let’s begin!
Find Your Bootcamp Match
- Career Karma matches you with top tech bootcamps
- Access exclusive scholarships and prep courses
Select your interest
First name
Last name
Phone number
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
The Problem: typeerror: a bytes-like object is required, not ‘str’
Let’s start by analyzing our error message:
typeerror: a bytes-like object is required, not 'str'
This error message gives us two vital pieces of information. TypeError tells us that we’re applying a function to a value of the wrong type.
The error message tells us that we’re treating a value like a string rather than a bytes-like object. Bytes-like objects are objects that are stored using the bytes data type. Bytes-like objects are not strings and so they cannot be manipulated like a string.
A Practice Scenario
This error is commonly raised when you open a file as a binary file instead of as a text file.
There’s no better way to solve an error than to walk through an example of a code snippet with that error. Below is a program that replicates this error:
with open("recipes.txt", "rb") as file:
recipes = file.readlines()
for r in recipes:
if "Chocolate" in r:
print(r)
This code snippet opens up the file “recipes.txt” and reads its contents into a variable called “recipes”.
The “recipes” variable stores an iterable object consisting of each line that is in the “recipes.txt” file. Next, we use a for loop to iterate over each recipe in the list.
In the for loop, we check if each line contains “Chocolate”. If a line contains the word “Chocolate”, that line is printed to the console. Otherwise, nothing happens.
Let’s run our code and see what happens:
Traceback (most recent call last): File "main.py", line 7, in <module> if "Chocolate" in r: TypeError: a bytes-like object is required, not 'str'
An error has been raised!
The Solution
The error “a bytes-like object is required, not ‘str’” tells us that we’ve tried to access an object as if it were a string when we should be accessing it as if it were a list of bytes.
The cause of this error is that we’ve opened our file “recipes.txt” as a binary:
with open("recipes.txt", "rb") as file:
Binary files are not treated as lines of text. Instead, they are treated as a series of bytes. This means that when we try to check if “Chocolate” is in each line in the file, an error is raised. Python doesn’t know how to check for a string in a bytes object.
We can solve this error by opening our file in read mode instead of binary read mode:
with open("recipes.txt", "r") as file:
Read mode is used to read text files. Binary read mode is used to read binary files. We’ve removed the “b” from the mode parameter to read our file in read mode. Let’s try to run our code again:
Chocolate Fudge Cake Chocolate Chip Cookie Chocolate Square
Our code works! Now that our file is read using read mode, our code can perform an “if…in” comparison to check if “Chocolate” is in each line in the “recipes.txt” file.
Bytes-Like Object Similar Error
The error we have been discussing is similar to the error “TypeError: X first arg must be bytes or a tuple of bytes, not str”.
You may encounter this error if you try to use a string method on a list of bytes. To solve this error, you can use the same approach that we used to solve the last error. Make sure that you open up any text files in text read mode instead of binary read mode.
Conclusion
The error “typeerror: a bytes-like object is required, not ‘str’” is raised when you treat an object as a string instead of as a series of bytes. A common scenario in which this error is raised is when you read a text file as a binary.
Now you’re ready to solve the bytes-like object error like a Python pro!
[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’ ?
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!

I am a professional Python Blogger and Content creator. I have published numerous articles and created courses over a period of time. Presently I am working as a full-time freelancer and I have experience in domains like Python, AWS, DevOps, and Networking.
You can contact me @:
UpWork
LinkedIn