1. 程式人生 > >python2 和python3 開啟檔案注意事項(兩者decode和encode函式的區別)

python2 和python3 開啟檔案注意事項(兩者decode和encode函式的區別)

比如,需要開啟的資料檔案puk_training.utf8的樣式如圖所示

一、python2 開啟檔案:

import sys
print(sys.getdefaultencoding()) #系統預設編碼方式

f = file(".\\pku_training.utf8") #以file來開啟檔案
print type(f)                    #獲取f的資料型別

data = f.read()[3:].decode('utf-8')  #比如讀取資料的的3及其以後資料,注意decode解碼
f.close()
print type(data)

data = data.encode('utf-8')  #以utf-8方式編碼
print type(data)

data = data.decode('utf-8')  #以utf-8方式解碼
print type(data)

tokens = data.split('  ') #以數按空格切分詞,存放到list裡邊
print type(tokens)        #列印tokens的資料型別
print type(tokens[1])     #列印tokens裡邊資料的資料型別

print tokens[1].encode('utf-8') #直接列印tokens[1]會出錯,需要列印str型別
print tokens[1]

輸出結果:

#輸出結果:
ascii

<type 'file'>

<type 'unicode'>

<type 'str'>

<type 'unicode'>

<type 'list'>

<type 'unicode'>

#測試資料型別列印
充滿 #tokens[1].encode('utf-8')的值
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)  #報錯,不能直接列印unicode編碼

python2中,我們使用decode()和encode()來進行解碼和編碼

在python2中,使用unicode型別作為編碼的基礎型別。即

      decode()               encode()

  str -----------> unicode ---------->str

注:python2中,不能直接列印unicode編碼,需要將unicode轉換成str才能進行列印輸出,否則會報錯。

二、python3開啟檔案

import sys
print(sys.getdefaultencoding()) #系統預設編碼方式

f=open(".\\pku_training.utf8", encoding='utf-8') # encoding表示編碼或者解碼的方式,此處為解碼
print(type(f))

data = f.read()[3:]
print(type(data))
f.close()

data = data.encode('utf-8')
print(type(data))

data = data.decode('utf-8')
print(type(data))

tokens = data.split('  ')
print(type(tokens))
print(type(tokens[1]))

print(tokens[1])  # str 型別可以列印
print(tokens[1].encode('utf-8')) # bytes 也可以列印

輸出結果:

#輸出結果:
utf-8

<class '_io.TextIOWrapper'>

<class 'str'>

<class 'bytes'>

<class 'str'>

<class 'list'>

<class 'str'>

#測試資料型別列印
充滿
b'\xe5\x85\x85\xe6\xbb\xa1'

python3中,encoding表徵的編碼或者解碼方式;

       decode()               encode()

  bytes -------------> str ------------->bytes

注:python 3中的str型別物件有點像Python2中的unicode,而decode是將str轉為unicode編碼,所以str僅有一個encode方法,呼叫這個方法後將產生一個編碼後的byte型別的字元。

python3 的print( )可以列印str和bytes行資料型別。

總結:

1、python2中的str對應python3中的bytes,unicode對應str;

2、python2系統預設編碼方式為ascii,而python3預設為utf-8;

參考: