實際案例
某文本文件編碼格式已知(如UTF-8燎悍,GBK飞蛹,BIG5)汛骂,在Python 2.X和Python 3.X中分別如何讀取該文件崖飘?
解決方案:
- Python 2.X:寫入文件前對Unicode編碼席镀,讀入文件后對二進制字符串編碼匹中;
- Python 3.X:open函數(shù)指定't'的文本模式,encoding指定編碼格式豪诲。
注:
字符串的語義發(fā)生了變化
Python 2.X Python 3.X
--------------------------------------------
str -> bytes
unicode -> str
Python 2.X版本的代碼如下:
# -*- coding: utf-8 -*-
# 打開文件
f = open('py2.txt', 'w')
s = u'你好'
# 寫入文件
f.write(s.encode('gbk'))
# 關(guān)閉文件
f.close()
f = open('py2.txt', 'r')
# 讀入文件
t = f.read().decode('gbk')
print t
f.close()
其運行結(jié)果為:
你好
Python 3.X版本的代碼如下:
# 打開文件
f = open('py3.txt', 'wt', encoding='utf8')
# 將“你好”寫入文件
f.write('你好')
# 關(guān)閉文件
f.close()
f = open('py3.txt', 'rt', encoding='utf8')
# 將文件內(nèi)容讀入
s = f.read()
print(s)
f.close()
其運行結(jié)果與Python 2.X版本代碼運行結(jié)果一致顶捷。