<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
- #&NBSP;CODING=GBK
- import urllib.request
- import re
- url = "http:// Www.163.com '
- file = "d:/ Test.html '
- data = urllib.request.urlopen (URL). read ()
- r1 = re.compile ( <.*?> "
- c_t = r1.findall (data)
- 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
- Import OS
-
- fname = "e:/data/ Html.txt '
- f = open (fname, ' R ' )
- html = f.read ()
- #print (HTML)
- print (Type ( html) #输出为 <class ' str ',
-
- u = html.encode ( ' Utf-8 ' Span style= "margin:0px; padding:0px; Border:none; Background-color:inherit; " >)
- 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