in Python by
TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3

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'

error on the last line (the pattern search code).

I've tried using the .decode() function on either side of the statement, also tried:

if tmp.find('some-pattern') != -1: continue

- to no avail.

I was able to resolve almost all 2:3 issues quickly, but this little statement is bugging me.

1 Answer

0 votes
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'.

Related questions

+1 vote
asked Feb 15, 2021 in Python by SakshiSharma
+1 vote
asked Jan 10, 2021 in Python by rajeshsharma
0 votes
asked Mar 16, 2021 in JAVA by Robindeniel