zoukankan      html  css  js  c++  java
  • 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




  • 相关阅读:
    Android自定义控件之仿美团下拉刷新
    Android性能优化之Bitmap的内存优化
    基于openfire+smack即时通讯instant message开发
    Android各组件/控件间通信利器之EventBus
    android的task任务栈
    Activity的启动模式
    Android 自定义View (一)
    Android之Handler用法总结
    Android中轻松使用线程
    Android 中Activity,Window和View之间的关系
  • 原文地址:https://www.cnblogs.com/highroom/p/61b0aae2e0dd257eb9321f09587da395.html
Copyright © 2011-2022 走看看