How to fix TypeError: a bytes-like object is required not ‘str’ in Python

A TypeError exception is raised when a function is called on an inappropriate type of object. In this particular error, the function expected a byte-like object, but instead, a string object was provided to it.

To understand how to solve this error, we have to first understand the difference between a byte string and a string. Python supports bytes and str objects. Byte objects are a sequence of binary characters. For example, ‘\xce\xb1\xce\xac’. These are not human-readable. However, these can be stored directly in the memory. However, string objects(eg- ‘αά’) are human-readable but cannot be stored directly in the memory.

We can convert an str object to a byte object by encoding it using the encode() function. Similarly, we can decode a byte object to an str object using the decode() function.

encode and decode

Now, the TypeError: a bytes-like object is required not ‘str’ is raised when you’re using a function that is expecting a byte object but you provided it with an str object. The error is seen while using various functions and operations in Python. Let’s discuss what is causing the issue in each case and possible fixes to overcome the error.

Also, check How to fix Attribute Error : ‘str’ object has no attribute ‘decode’ in Python 3

Case 1- TypeError: a bytes-like object is required not ‘str’ while Reading and writing the Files

When you open the file in “wb” mode, you have to write byte strings into the file. If you try to write string objects, you see an error. Similarly, you see an error when you try to read a binary file in text mode.

Consider the below example, when you try to open the file in binary mode and try to write string objects, an error is seen.

with open("demo.txt",'wb') as f:
    f.write('abc')
print("Executed successfully")

Output:

Traceback (most recent call last):
  File "C:\Users\paian\PycharmProjects\PythonHowTo\venv\Solutions\Test.py", line 2, in <module>
    f.write('abc')
TypeError: a bytes-like object is required, not 'str'

Solution 1:

To fix this error, use “w” mode and write strings. Refer to the below example

with open("demo.txt",'w') as f:
    f.write('abc')
print("Executed successfully")

Output:

Executed successfully

Solution 2:

Alternatively, you can use “wb” mode and write byte strings as shown below

with open("demo.txt",'wb') as f:
    f.write(b'abc')
print("Executed successfully")

Output:

Executed successfully

 

Case 2- TypeError: a bytes-like object is required not ‘str’ while writing the CSV files

If you are trying the convert the code written in Python 2 to Python 3 and seeing this error, it is important to note that in Python 2 the CSV files had to be opened in binary mode, that is using the mode s rb, wb, etc. However, from Python 3 onwards, the CSV files can be opened and edited in the text mode itself, that is the modes r,w, etc.

 

import csv

with open("sample.csv",'w') as f:
    f.write('abc')

 

Case 3- TypeError: a bytes-like object is required not ‘str’ while using split()

If you see the TypeError when you’re using the split() function, that is because you are trying to call a split() function on a byte string and split it based on a string object. Refer to the below example:

my_str=b'Welcome to PythonHowTo.Lets learn Python together'
print(my_str.split("."))

Output:

Traceback (most recent call last):
  File "C:\Users\paian\PycharmProjects\PythonHowTo\venv\Solutions\Test.py", line 2, in <module>
    print(my_str.split("."))
TypeError: a bytes-like object is required, not 'str'

In the above code snippet, we are seeing an error because my_str is a byte string object and we are trying to split it based on string object”.

Solution 1:

You can decode the byte string using the decode() function and then split the string as shown below.

my_str=b'Welcome to PythonHowTo.Lets learn Python together'
print(my_str.decode().split("."))

Output:

['Welcome to PythonHowTo', 'Lets learn Python together']

 

Solution 2:

If you are expecting the output in byte string format, instead of decoding the string, you can also encode the string in the spilt() function as shown below.

my_str=b'Welcome to PythonHowTo.Lets learn Python together'
print(my_str.split(".".encode()))

Output:

[b'Welcome to PythonHowTo', b'Lets learn Python together']

Note: 

Converting the string object within the split() to a byte object using the b'<string>’ is not recommended at all times. Use it only when the byte string is the human-readable format. Consider the below examples,

>>”.”.encode()
b’.’
>>’αά’.encode()
b”‘\xce\xb1\xce\xac'”

b’.’ corresponds to string “.”. But  a character like ‘αά’ is not equivalent to b’αά’

 

Case 4- TypeError: a bytes-like object is required not ‘str’ while using replace()

If you have a byte string and try to replace it with a string object, you see this error. Refer to the below example.

my_str=b'Welcome to PythonHowTo.Lets learn Python together'
print(my_str.replace(b"PythonHowTo","PythonHowTo.com"))

Output:

Traceback (most recent call last):
  File "C:\Users\paian\PycharmProjects\PythonHowTo\venv\Solutions\Test.py", line 2, in <module>
    print(my_str.replace("PythonHowTo","PythonHowTo.com"))
TypeError: a bytes-like object is required, not 'str'

In the above code snippet, my_str is a byte string, when you replace it with a string object an error is seen.

Solution 1:

If you are expecting the output in string format, decode the string and then call the replace()

 

my_str=b'Welcome to PythonHowTo.Lets learn Python together.'
print(my_str.decode().replace("PythonHowTo","PythonHowTo.com"))

Output:

Welcome to PythonHowTo.com.Lets learn Python together.

Solution 2:

If you want the output in byte string format, convert the string within replace() to byte string with encode() or b'<string>’ as shown below.

my_str=b'Welcome to PythonHowTo.Lets learn Python together.'
print(my_str.replace(b"PythonHowTo",b"PythonHowTo.com"))

Output:

b'Welcome to PythonHowTo.com.Lets learn Python together.'

Note: 

Converting the string object within the split() to a byte object using the b'<string>’ is not recommended at all times. Use it only when the byte string is in a human-readable format.

 

Case 5- TypeError: a bytes-like object is required not ‘str’ with ByteIO()

When you’re using the io module in your program, if the file contains strings and you’re using ByteIO() to read the file, this error is seen.

Instead of

stream=ByteIO()

use

stream=StringIO()

Case 6- TypeError: a bytes-like object is required not ‘str’  while using socket

When you’re working with the socket module, the bytes strings must be provided as a parameter to the send, sendall,sendto methods. Consider the below example:

import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('www.pythonhowto.com', 80))
mysock.send('GET https://www.pythonhowto.com/home/romeo.txt HTTP/1.0\n\n')

Output:

Traceback (most recent call last):
  File "C:\Users\paian\PycharmProjects\PythonHowTo\venv\Solutions\Test.py", line 4, in <module>
    mysock.send('GET https://www.pythonhowto.com/home/romeo.txt HTTP/1.0\n\n')
TypeError: a bytes-like object is required, not 'str'

Solution 1:

To fix the error, convert the string to byte-strings when you have URL sort-of data as shown below.

import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('www.pythonhowto.com', 80))
mysock.send(b'GET https://www.pythonhowto.com/home/romeo.txt HTTP/1.0\n\n')

Solution 2:

When you have a string type of object to be sent, it is better to use encode() function to convert the string to byte string object as shown below.

import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('www.pythonhowto.com', 80))
msg="Hello"
mysock.send(msg.encode())

Conclusion

That brings us to the end of this tutorial. In this short tutorial, we have learned what causes the TypeError: a bytes-like object is required not ‘str’, and discussed possible solutions for the same. We hope this has been informative. Thank you for reading. Do come back to us for more interesting content.

If you enjoyed reading, share this article.

Anusha Pai is a Software Engineer having a long experience in the IT industry and having a passion to write. She has a keen interest in writing Python Errorfixes, Solutions, and Tutorials.

Leave a Comment