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

Hello readers, Today In this article I am going to show you how to Solved – typeerror: a bytes-like object is required, not ‘str’ error in python.

Without wasting your time, Let’s start This Article to Solve This Error.

How to TypeError: a bytes-like object is required, not ‘str’ Error Occurs?

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'

Binary files are considered a series of bytes data and not as a string. This means that all data read from the file is returned as bytes objects, not str. You cannot then use a string in a containment test:

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

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

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

Summary

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you?

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Categories