Sometimes, we want to fix TypeError: a bytes-like object is required, not ‘str’ when writing to a file in Python 3.
In this article, we’ll look at how to fix TypeError: a bytes-like object is required, not ‘str’ when writing to a file in Python 3.
How to fix TypeError: a bytes-like object is required, not ‘str’ when writing to a file in Python 3?
To fix TypeError: a bytes-like object is required, not ‘str’ when writing to a file in Python 3, we can open the file with open and 'r‘.
For instance, we write
with open(fname, 'r') as f:
# ...
to open the file at path fname with open.
We open it with read permission as a string with 'r'.
Conclusion
To fix TypeError: a bytes-like object is required, not ‘str’ when writing to a file in Python 3, we can open the file with open and 'r‘.