Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3

I've very recently migrated to Py 3.5. This code was working properly in Python 2.7:

with open(fname, 'rb') as f:     lines = [x.strip() for x in f.readlines()]  for line in lines:     tmp = line.strip().lower()     if 'some-pattern' in tmp: continue     # ... code 

After upgrading to 3.5, I'm getting the:

TypeError: a bytes-like object is required, not 'str' 

error on the last line (the pattern search code).

I've tried using the .decode() function on either side of the statement, also tried:

if tmp.find('some-pattern') != -1: continue 

- to no avail.

I was able to resolve almost all 2:3 issues quickly, but this little statement is bugging me.

like image 618
masroore Avatar asked Oct 10 '15 13:10

masroore


People also ask

What is Typeerror a bytes-like object is required not str?

The error “typeerror: a bytes-like object is required, not 'str'” is raised when you treat an object as a string instead of as a series of bytes. A common scenario in which this error is raised is when you read a text file as a binary.

Is a string a bytes-like object?

Bytes-like object in python In Python, a string object is a series of characters that make a string. In the same manner, a byte object is a sequence of bits/bytes that represent data. Strings are human-readable while bytes are computer-readable. Data is converted into byte form before it is stored on a computer.

How do you encode a byte in Python?

We can use the built-in Bytes class in Python to convert a string to bytes: simply pass the string as the first input of the constructor of the Bytes class and then pass the encoding as the second argument. Printing the object shows a user-friendly textual representation, but the data contained in it is​ in bytes.


1 Answers

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 

You'd have to use a bytes object to test against tmp instead:

if b'some-pattern' in tmp: continue 

or open the file as a textfile instead by replacing the 'rb' mode with 'r'.

like image 58
Martijn Pieters Avatar answered Oct 13 '22 18:10

Martijn Pieters