Skip to main content
10 of 13
Second iteration.
Peter Mortensen
  • 31.4k
  • 22
  • 110
  • 134

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

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 

After upgrading to 3.5, I'm getting the:

TypeError: a bytes-like object is required, not 'str'

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

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

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

- to no avail.

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

masroore
  • 10.2k
  • 4
  • 29
  • 31