. Advertisement .
..3..
. Advertisement .
..4..
Hey, geys! I am confused with the typeerror: a bytes-like object is required, not ‘str’ in Python. I am having the this file, I save it with the file_sample.txt
name:
product;stock;price
bike;10;50
laptop;3;1000
microphone;5;40
book;3;9
Then I write the following program:
with open('file_sample.txt', 'rb') as f:
lines = [x.strip() for x in f.readlines()]
bike_available = False
for line in lines:
tmp = line.strip().lower()
split_line = tmp.split(';')
if split_line[0]=='bike' and int(split_line[1])>0:
bike_available = True
print("Bikes Available? "+ str(bike_available))
Here is the output:
Traceback (most recent call last):
Error line 7, in <module>
splitted_line = tmp.split(';')
TypeError: a bytes-like object is required, not 'str'
I have read a lot of documents, but I don’t know how to fix it. Does someone guide me to solve this error? Thanks!
The cause:
You used
with open('file_sample.txt', 'rb')
to open the file.rb
indicates that the file need to be opened in reading binary mode. Binary mode is reading the data in the form of bytes objects. If you examine line 7, you will notice that you are attempting to split a byte object with a string. Therefore, the operation returns a TypeError.Solution:
To solve this error, the types which the
split()
operation uses need to match together. The best way is changing the delimiter to a byte object. I have successed by adding the string withb
prefix as following:This is the output:
I also prefixed the
b
or added bytes conversion to theif split_line[0]==b'bike'
condition, so the types also match, and the comparison is accurate.I removed the
b
from theopen()
action and the error disappeared.Output is: