Home >Backend Development >Python Tutorial >How to Resolve 'TypeError: a bytes-like object is required, not 'str'' in Python 3 File Handling?
Python 3.5 File Handling: "TypeError: a bytes-like object is required, not 'str'" Resolved
When working with file content in Python 3, it is essential to understand the difference between bytes and strings. In Python 3, files are opened in binary mode by default, and content is returned as bytes objects.
To fix the error "TypeError: a bytes-like object is required, not 'str'," when dealing with file content, there are two main solutions:
1. Open the File as Text
with open(fname, 'r') as f: lines = [x.strip() for x in f.readlines()]
This method opens the file in text mode, ensuring that the data is returned as strings.
2. Use Bytes Objects
If it is necessary to work with bytes objects, the code can be modified to use bytes instead of strings:
if b'some-pattern' in tmp: continue
It is important to note that when working with bytes objects, comparison operators such as 'in' and '==' require the use of bytes on both sides.
The above is the detailed content of How to Resolve 'TypeError: a bytes-like object is required, not 'str'' in Python 3 File Handling?. For more information, please follow other related articles on the PHP Chinese website!