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

Created by Martijn PietersLinked to 85.3m issues across 79 teams


When working with file content in Python 3, you may encounter the error "TypeError: a bytes-like object is required, not 'str'". This is a common error and it's caused by opening the file in binary mode, which means that all data read from the file is returned as bytes objects, not str:

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

To fix this, you can either use a bytes object to test against the data instead of a string, or open the file as a textfile instead. To use a bytes object, you need to add a 'b' before the string you are testing against, like this:

`if b'some-pattern' in tmp: continue`

To open the file as a textfile, replace the 'rb' mode with 'r'. This will allow you to use strings in a containment test.