Programmers learn & share
0 votes
662 views

Problem :

I am new  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'
by (6.9k points)   | 662 views

2 Answers

0 votes

Solution :

It seems you opened the file in binary mode:

with open(fname, 'rb') as f:

This means that all data is read from the file  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'.

Further Readings:

https://github.com/mitsuhiko/phpserialize/issues/15

by (36.1k points)  
edited by
0 votes

Solution:

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'.

You can get rid of the error by using the below-mentioned way:-

And the reason you are getting that error is in Python 3, strings are Unicode, but when transmitting on the network, the data needs to be bytes strings instead. So... a couple of suggestions:

  1. The first thing you can use is c.sendall() method instead of c.send() to prevent possible issues where you may not have sent the entire msg with one call.

  2. For literals, add a 'b' for bytes string: c.sendall(b'Thank you for connecting')

  3. For variables, you need to encode Unicode strings to byte strings (see below)

Below is the code which will work both on Python 2.0 as well as Python 3.0:-
output = 'Thank you for connecting'

c.sendall(output.encode('utf-8'))

 

ago by (5.5k points)  
2,187 questions
2,514 answers
59 comments
241 users