Type error: a bytes-like object is required, not 'str'| Query Bro





First 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 text file instead by replacing the 'rb' mode with 'r'.



Second Solution: -

You can encode your string by using .encode()

Example: 

'Hello World'.encode()

As the error describes, in order to write a string to a file you need to encode it to a byte-like object first, and encode() is encoding it to a byte-string.


Previous Post Next Post