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') #指定文件的編碼格式

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM