Python 3.5:typeerror:a Bytes-like object is required, not ' str '

Source: Internet
Author: User

The error often occurs when opening a text file through the open () function, using the ' RB ' attribute, such as: Filehandle=open (filename, ' RB '), when the file is opened in binary mode, so if the STR () function is used in the later processing, The error will occur, and the error will no longer appear in the Python2.

There are two ways to solve the problem:

The first, using the ' R ' attribute in the open () function, which reads text, instead of ' RB ', is read in binary file, which solves the problem directly.

The second, using ' RB ' in the open () function, can be converted before use, with the following example from: http://stackoverflow.com/questions/33054527/ Python-3-5-typeerror-a-bytes-like-object-is-required-not-str

1: When locating a file: With open (fname, ' RB ') as F:                if B ' some-pattern ' in tmp:continue2: When using socketl connection: Mysock = socket.socket (socket . af_inet, Socket. Sock_stream) Mysock.connect ((' www.py4inf.com ',) mysock.send (**b** ' GET http://www.py4inf.com/code/romeo.txt http /1.0\n\n ') while True:    data = MYSOCK.RECV (+)    if (len (data) < 1):        break    print (data); Mysock.close ( ) 3: Encode in advance: with open (fname, ' RB ') as F:    lines = [X.decode (' UTF8 '). "Strip () for x in F.readlines ()]

Python 3.5:typeerror:a Bytes-like object is required, not ' str '

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.