patternpythonCritical
"TypeError: a bytes-like object is required, not 'str'" when handling file content in Python 3
Viewed 0 times
handlingobjectstrpythontypeerrorlikefilebytescontentnot
Problem
I've very recently migrated to Python 3.5.
This code was working properly in Python 2.7:
But in 3.5, on the
I was unable to fix the problem using
What is wrong, and how do I fix it?
This code was working properly in Python 2.7:
with open(fname, 'rb') as f:
lines = [x.strip() for x in f.readlines()]
for line in lines:
tmp = line.strip().lower()
if 'some-pattern' in tmp: continue
# ... code
But in 3.5, on the
if 'some-pattern' in tmp: continue line, I get an error which says:TypeError: a bytes-like object is required, not 'str'
I was unable to fix the problem using
.decode() on either side of the in, nor could I fix it using if tmp.find('some-pattern') != -1: continue
What is wrong, and how do I fix it?
Solution
You opened the file in binary mode:
This means that all data read from the file is returned as
You'd have to use a
or open the file as a textfile instead by replacing the
with open(fname, 'rb') as f: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:if 'some-pattern' in tmp: continueYou'd have to use a
bytes object to test against tmp instead:if b'some-pattern' in tmp: continueor open the file as a textfile instead by replacing the
'rb' mode with 'r'.Code Snippets
with open(fname, 'rb') as f:if 'some-pattern' in tmp: continueif b'some-pattern' in tmp: continueContext
Stack Overflow Q#33054527, score: 812
Revisions (0)
No revisions yet.