python – TypeError: a bytes-like object is required, not str when writing to a file in Python3
python – TypeError: a bytes-like object is required, not str when writing to a file in Python3
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
Youd have to use a bytes
object to test against tmp
instead:
if bsome-pattern in tmp: continue
or open the file as a textfile instead by replacing the rb
mode with r
.
You can encode your string by using .encode()
Example:
Hello World.encode()
python – TypeError: a bytes-like object is required, not str when writing to a file in Python3
Like it has been already mentioned, you are reading the file in binary mode and then creating a list of bytes. In your following for loop you are comparing string to bytes and that is where the code is failing.
Decoding the bytes while adding to the list should work. The changed code should look as follows:
with open(fname, rb) as f:
lines = [x.decode(utf8).strip() for x in f.readlines()]
The bytes type was introduced in Python 3 and that is why your code worked in Python 2. In Python 2 there was no data type for bytes:
>>> s=bytes(hello)
>>> type(s)
<type str>