• Register
Welcome to Kodlogs, programming questions and answer website.
0 votes
47 views

Problem :

I am new  to Py 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

After upgrading to 3.5, I'm getting the:

TypeError: a bytes-like object is required, not 'str'
by (6.9k points)  

1 Answer

0 votes

Solution :

It seems you opened the file in binary mode:

with open(fname, 'rb') as f:

This means that all data is read from the file  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'.

Further Readings:

https://github.com/mitsuhiko/phpserialize/issues/15

by (21.9k points)  
edited by
...