Python3 读写文件碰到的编码问题

Python3 读写文件碰到的编码问题

1,远程文件资源读取 response的为 bytes,即utf-8或者gbk,需解码decode为unicode

如:

[python] view plaincopy在CODE上查看代码片派生到我的代码片
  1. # 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)  

发现读取下来后,运行到第9 行,出现:

can't use a string pattern on a bytes-like object

查找了一下,是说3.0现在的参数更改了,现在读取的是bytes-like的,但参数要求是chart-like的,找了一下,加了个编码:

data = data.decode('GBK')

在与正则使用前,就可以正常使用了..


2.读取本地文本文件open(fname)的为str,即unicode,需编码为encode(utf-8")

如:

[python] view plaincopy在CODE上查看代码片派生到我的代码片
  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')  
  10. print (type(u))<span style="white-space:pre">           </span>#输出为 <class 'bytes'>  
在python3中 <str>型为unicode




posted @ 2015-02-06 16:31  阳光树林  阅读(2037)  评论(0编辑  收藏  举报