Table of Contents
◈ Problem Formulation
Suppose you have the following file given below and you want to check the price for a certain product.
Now, you want to check the price for Samsung Galaxy S21
using the following piece of code:
1 2 3 4 5 6 7 8 9 10 11 |
with open('file.txt', 'rb') as f: lines = [x.strip() for x in f.readlines()] for line in lines: tmp = line.strip() split_line = tmp.split('-') price = (str(split_line[1]).replace(' ', '')) if split_line[0] == 'Samsung Galaxy S21 ': print("Price = ", split_line[1]) |
But when you execute your code, you receive the following output:
Output:
1 2 3 4 5 6 |
Traceback (most recent call last): File "D:/PycharmProjects/pythonProject1/TypeError.py", line 6, in <module> split_line = tmp.split('-') TypeError: a bytes-like object is required, not 'str' |
So, this brings us to the question – What is a TypeError? What causes such errors in our program?
Hence, without further delay let us understand the reason behind the occurrence of TypeError
and the ways to fix such errors.
◈ What Is TypeError in Python?
A TypeError
is generally raised when a certain operation is applied to an object of an incorrect type.
Example:
1 2 3 |
print('Java'+2+'Blog') |
Output:
1 2 3 |
TypeError: can only concatenate str (not "int") to str |
In the above, we tried to add a string object and an integer object using the + operator. This is not allowed and hence we encountered a TypeError
.
There can be numerous reasons that lead to the occurrence of TypeError
. Some of these reasons are:
- Trying to perform an unsupported operation between two types of objects.
- Trying to call a non-callable caller.
- Trying to iterate over a non-iterative identifier.
Now that we have a clear idea about TypeErrors
, let us find out the reason behind the occurrence of TypeError
error in our code.
☞ How To Fix TypeError: A Bytes-Like object Is Required, Not ‘str’
We opened the file as: with open('file_sample.txt', 'rb')
. Here rb
denotes binary mode which means that all the data being read from the file is returned as bytes
. Hence, when you look at line 6, you will find that we are trying to split a byte object using a string. This operation is not allowed and leads to to a TypeError
.
So, how do we fix this error in our program? 🤔 Let’s dive into the methods to solve our problem!
✨Method 1: Convert To Bytes Object
The easiest solution to our problem is to ensure that the object types match by converting the delimiter string within the split()
function to a byte object. You can achieve this by using the prefix b
before the delimiter string within the split()
function. This allows you to operate upon a byte object within the split()
function, thereby avoiding the TypeError
.
Solution:
1 2 3 4 5 6 7 8 9 10 |
with open('file.txt', 'rb') as f: lines = [x.strip() for x in f.readlines()] for line in lines: tmp = line.strip() split_line = tmp.split(b'-') if split_line[0] == b'Samsung Galaxy S21 ': print("Price = ", split_line[1]) |
Output:
1 2 3 |
Price = b' Rs.1,05,999.00 ;' |
✨ Method 2: Using decode()
In our code, we are trying to read the file in binary mode and then creating a list of bytes. In the for loop, we are comparing the string to bytes and that is exactly where the code is failing. So to overcome this, you can decode the bytes while adding them to the list using the decode()
function.
❖ The decode()
method allows you to convert from one encoding scheme, in which the argument string is encoded to another desired encoding scheme.
Let us have a look at the following code to understand how we can fix the TypeError
in our code.
1 2 3 4 5 6 7 8 9 10 11 |
with open('file.txt', 'rb') as f: lines = [x.decode('utf8').strip() for x in f.readlines()] for line in lines: tmp = line.strip() split_line = tmp.split('-') if split_line[0] == 'Samsung Galaxy S21 ': print("Price = ", split_line[1]) |
Output:
1 2 3 |
Price = Rs.1,05,999.00 ; |
✨ Method 3: Using Encode()
❖ The encode()
method in Python is used to encode the string, using the specified encoding.
Therefore, you can encode the delimiter string within the split()
function using .encode()
and then proceed with the next steps in your program as shown below.
1 2 3 4 5 6 7 8 9 10 11 |
with open('file.txt', 'rb') as f: lines = [x.strip() for x in f.readlines()] for line in lines: tmp = line.strip() split_line = tmp.split('-'.encode()) if 'Samsung Galaxy S21 ' in str(split_line[0]): print("Price = ", split_line[1]) |
Output:
1 2 3 |
Price = b' Rs.1,05,999.00 ;' |
✨ Method 4: Open The File in Text Mode
Another work-around to our problem is to open the file in text mode. You can achieve this by using rt
instead of rb
inside the open()
function.
Solution:
1 2 3 4 5 6 7 8 9 10 11 |
with open('file.txt', 'rt') as f: lines = [x.strip() for x in f.readlines()] for line in lines: tmp = line.strip() split_line = tmp.split('-') if 'Samsung Galaxy S21 ' in str(split_line[0]): print("Price = ", split_line[1]) |
Output:
1 2 3 |
Price = Rs.1,05,999.00 ; |
Conclusion
In this article we learned:
- What is
TypeError
? - Reasons behind
TypeError
? - How To Fix TypeError: A Bytes-Like object Is Required, Not ‘str’?
- Method 1: By Converting Types to Byte type object.
- Method 2: Using
encode()
function. - Method 3: Using
decode()
function. - Method 4: Opening the file in text mode.
With that, we come to the end of this article and I hope you enjoyed learning! Please subscribe and stay tuned for more interesting articles and discussions in the future. Happy Learning! 📚