sublime python3中读取和写入文件时如何解决编码问题

# -*- coding: utf-8 -*-
#分析用户身份审核信息
#python 3.5
#xiaodeng
#http://apistore.baidu.com/apiworks/servicedetail/113.html

import urllib.parse
import urllib.request
import time


#python UnicodeDecodeError: 'gbk' codec can't decode byte 0xff in position 0
#解决以上编码错误问题
#encoding= 'utf8'
data=open("cardno.txt",encoding= 'utf8')

result=open("result.txt","w",encoding= 'utf8')     #指定文件的编码格式
url = "http://apis.baidu.com/apistore/idservice/id?id="

for k in data:
    k=k.strip()
    k=k.split('\t')
    uid=k[0]
    name=k[1]
    cardno=str(k[2])
    print(cardno)
    My_url=url+cardno
    time.sleep(0.1)
    try:
        req = urllib.request.Request(My_url)
        req.add_header("apikey","xxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
        response = urllib.request.urlopen(req)
        the_page = response.read()
        try:
            the_page=eval(the_page)
            try:
                retData=the_page["retData"]
                birthday=retData["birthday"]
                sex=retData["sex"]
                address=retData["address"]

                result.write("%s\t%s\t%s"%(sex,birthday,address)+"\n")
            except:
                result.write("%s\t%s\t%s"%("数据错误","数据错误","数据错误")+"\n")
        except Exception as err:
            print(err)
    except Exception as err:
            print(err)

result.close()
在打开和写入文件时,写明编码格式即可
encoding='utf8'

data=open("cardno.txt",encoding= 'utf8') result=open("result.txt","w",encoding= 'utf8') #指定文件的编码格式

 

posted @ 2016-11-13 17:22  Xiao|Deng  阅读(12638)  评论(2编辑  收藏  举报