Coding problems encountered by Python3 read-write files

Source: Internet
Author: User

<title>Coding problems encountered by Python3 read-write files</title>

1, remote file resource read response for bytes, that is utf-8 or GBK, need to decode decode for Unicode

Such as:

[Python]View Plaincopy
  1. #&NBSP;CODING=GBK
  2. import   urllib.request  
  3. import  re   
  4. url =   "http:// Www.163.com '
  5. file =   "d:/ Test.html '
  6. data =  urllib.request.urlopen (URL). read ()   
  7. r1 =  re.compile ( <.*?> "
  8. c_t =  r1.findall (data)   
  9. Print (c_t)

After the discovery reads down, runs to line 9th, which appears:

Can ' t use a string pattern on a Bytes-like object

Looked up, is said 3.0 now the parameter changes, now read is bytes-like, but the parameter requirements are chart-like, look for a bit, add a code:

data = Data.decode (' GBK ')

It can be used normally before it is used in regular use.


2. read local text File open (fname) for STR, i.e. Unicode, to be encoded as encode (utf-8 ")

Such as:

[Python]View Plaincopy
  1. Import OS
  2.   
  3. fname =   "e:/data/ Html.txt '
  4. f =  open (fname, ' R ' )   
  5. html =  f.read ()   
  6. #print (HTML)    
  7. print   (Type ( html)               #输出为  <class  ' str ',   
  8.   
  9. u =  html.encode ( ' Utf-8 ' Span style= "margin:0px; padding:0px; Border:none; Background-color:inherit; " >)   
  10. print   (Type (U)) <span style= "White-space:pre" #输出为  <class  ' bytes ',   
in Python3, the <str> type is Unicode


From for notes (Wiz)

Coding problems encountered by Python3 read-write files

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.