HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonCritical

"TypeError: a bytes-like object is required, not 'str'" when handling file content in Python 3

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
handlingobjectstrpythontypeerrorlikefilebytescontentnot

Problem

I've very recently migrated to Python 3.5.
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:

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: continue


You'd have to use a bytes object to test against tmp instead:

if b'some-pattern' in tmp: continue


or 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: continue
if b'some-pattern' in tmp: continue

Context

Stack Overflow Q#33054527, score: 812

Revisions (0)

No revisions yet.