error solved

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


In this article, you will learn how to solve typeerror: a bytes-like object is required, not ‘str’ error in Python.

Let’s look at a code example that produces the same error.

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

for r in fruits:
	if "mango" in r:
		print(r)

Output

TypeError: a bytes-like object is required, not 'str'

In order to solve typeerror: a bytes-like object is required, not ‘str’ error in Python we need to open fruits.txt as read mode, in the above code snippet we tried to open txt file as binary. Consider the the correct code snippet below:

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

for r in fruits:
	if "mango" in r:
		print(r)

Share on social media

//