python

TypeError: a bytes-like object is required, not ‘str’ – Python3

This tutorial guides you on how to resolve TypeError: a bytes-like object is required, not ‘str’ while running Python3 scripts. TypeErrors are common while executing python scripts and I got this error message when tried to open a file and iterate over each name. Let’s understand more with an example.

TypeError: a bytes-like object is required, not ‘str’ – Python3

For example, you have the following code sneppet, which opens up a file called “names.txt” and reads its content into a variable called “names“.

names.py

with open("names.txt", "rb") as file:
	names = file.readlines()

for r in names:
	if "john" in r:
		print(r)

The names.txt file has the following content.

names.txt

john
peter
michael
daniel

When names.py is run, I got the following error which says that you are treating objects like a string objects instead of bytes-like objects. Therefore, you need to treat them as byte-like object and not like string.

> python names.py

Traceback (most recent call last):
  File "names.py", line 5, in <module>
    if "john" in r:
TypeError: a bytes-like object is required, not 'str'

Solution : Bytes-like object and str

Note, bytes-like objects are the objects which are stored using data type called bytes. Hence, byte-like objects cannot be treated like string while iteration/ manipulation.

Therefore, the TypeError: a bytes-like object is required, not ‘str’ tells us we are opening file as a binary file (binary mode) instead of as a text file. The value “rb” indicates that we are trying to open a file with binary read (rb) mode.

with open("names.txt", 'rb') as f:

Hence, you need to open “names.txt” file in read mode and not in binary read mode. Also, this error can be solved by just changing the mode from binary read mode to read mode (“r”) as shown below.

with open("names.txt", "r") as file:

Note, it is important for you to understand that read mode “r” should be used to read text files and binary read “rb” mode should be used to read binary files.

After you modify the names.py code, it should look like as shown below.

with open("names.txt", "r") as file:
	names = file.readlines()

for r in names:
	if "john" in r:
		print(r)

Let’s try to run names.py again.

> python names.py

john

Yay! the code changes worked. And the TypeError is fixed now.

Hope it helped 🙂

You’ll also like:

References

guest
0 Comments
Inline Feedbacks
View all comments