Python typeerror: a bytes-like object is required, not ‘str’

Python Typeerror A Bytes-Like Object Is Required, Not 'Str'
Python typeerror a bytes-like object is required, not ‘str’

What is TypeError in Python?

The typeerror: a bytes-like object is required, not ‘str’ is generally raised when a certain operation is applied to an object of the incorrect type. 

If you look at the error, it states that it requires a byte-like object, but instead, a string is passed to the function. In general, such an error occurs if you pass the wrong argument to a function.

typeerror: a bytes-like object is required, not ‘str’

The error occurs when you open a file in binary format rather than as a read-only text file. Let’s take a look at some real-time examples.

# Create a file in Python and write contents to it
testFile = open("sample.txt", "w+")
for i in range(1):
    testFile.write("Fruits,Apple\n")
    testFile.write("Fruits,Orange\n")
testFile.close()


# Reading a file in Python in binary format

with open("sample.txt", 'rb') as file:
    content= file.readlines()
for r in content:
    if "Fruits" in r:
        print(r)

Output

Fruits,Apple
Fruits,Orange

The above code will create a “sample.txt” file with the content Hello world. Next, we are trying to open and read the file in binary format and print the content. The moment you execute this code, you will get a typeerror: a bytes-like object is required, not ‘str’

A solution to typeerror: a bytes-like object is required, not ‘str’

Binary files are considered a series of bytes data and not as a string. It means that all data read from the file is returned as bytes objects, not str. 

We can solve this error by opening the file in read-only mode instead of binary mode, as shown below.  

# Reading a file in Python in string format

with open("sample.txt", 'r') as file:
    content= file.readlines()
for r in content:
    if "Fruits" in r:
        print(r)

Output

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

Bytes-Like Object Similar Error in .replace()

The method .replace() is used to replace a particular phrase of a string with another phrase, and you could find this error when you are trying to use the .replace() method and the types are not matching. Here is an example:

text1=b"Welcome to paradise"
text2=text1.replace("paradise","heaven")
print(text2)

Output

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

Solution Bytes-Like Object Similar Error in .replace()

You can avoid this problem by making sure the types are matching while using replace method. Therefore one possible solution is converting the string passed into the .replace() function( line 2), as follows:

text1=b"Welcome to paradise"
text2=text1.replace(b"paradise",b"heaven")
print(text2)

Output

b'Welcome to heaven'

Typeerror: a bytes-like object is required, not ‘str’ socket

If you are using socket to send any data you will encounter an error a bytes-like object is required, not ‘str’ 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.google.com', 80))
mysock.send('GET https://itsmycode.com/sample.txt HTTP/1.0\n\n')

while True:
    data = mysock.recv(512)
    if ( len(data) < 1 ) :
        break
    print (data);
mysock.close()

Output

Traceback (most recent call last):
  File "<string>", line 4, in <module>
        mysock.send('GET https://itsmycode.com/sample.txt HTTP/1.0\n\n')
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 as shown below or you can append .encode() at the end and other way is to use encode:

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

while True:
    data = mysock.recv(512)
    if ( len(data) < 1 ) :
        break
    print (data);
mysock.close()

Alternatively, you could use string.encode() to convert from String to Bytes and string.decode() to convert from Bytes to String. We will explore in depth on this topic in another article.

Leave a Reply

Your email address will not be published. Required fields are marked *

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like