In today’s tutorial we will learn to troubleshoot one common error we encounter when working with external files in Python3.
In order to make your Python code more robust and platform agnostic you might have decided to open any file that you interact with in binary mode. Then, when trying to interact with the binary content without properly encoding it, the Python interpreter will throw an error. Here’s a simple example:
file_path = 'C:\MyDir\myfile.txt' # we open the file in binary mode and read its contents with open (file_path,'rb') as f: output_file =f.readlines() # we then search for a string in each line key_word = 'Copyright' for line in output_file: if key_word in line: print(line)
This code snippet will throw the following error:
TypeError: a bytes-like object is required, not 'str'
Note: the error will be thrown whenever you try to perform string operations such as split, join, capitalize and format, on bytes-like data.
Fixing the typeerror bytes-like object required
You can encode the string that you would like to search for accordingly so that your string can be treated as a bytes-like object:
for line in output_file: if key_word.encode() in line: print(line)
Solution # 2
A second possible way to solve this error is to open your file in normal text read mode. Note that this method is less robust as it affects your code’s cross-platform portability.
file_path = 'C:\MyDir\myfile.txt' # we open the file in read mode and read its contents with open (file_path,'r') as f: output_file =f.readlines() # we then search for a string in each line #.......
Note: The code provided above, will function as prescribed also when interacting with additional file types such as pickle, csv, json and so forth.