实际案例
某文本文件编码格式已知(如UTF-8,GBK,BIG5),在Python 2.X和Python 3.X中分别如何读取该文件?
解决方案:
Python 2.X:写入文件前对Unicode编码,读入文件后对二进制字符串编码;
Python 3.X:open函数指定't'的文本模式,encoding指定编码格式。
注:
字符串的语义发生了变化
Python 2.X Python 3.X
--------------------------------------------
str -> bytes
unicode -> str
Python 2.X版本的代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# -*- coding: utf-8 -*- # 打开文件 f = open('py2.txt', 'w') s = u'你好' # 写入文件 f.write(s.encode('gbk')) # s.encode('gbk') 编码 # 关闭文件 f.close() f = open('py2.txt', 'r') # 读入文件 t = f.read().decode('gbk') # .decode('gbk') 解码 print t f.close() |
其运行结果为:
1 |
你好 |
Python 3.X版本的代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
# 打开文件 f = open('py3.txt', 'wt', encoding='utf8') # 将“你好”写入文件 f.write('你好') # 关闭文件 f.close() f = open('py3.txt', 'rt', encoding='utf8') # 将文件内容读入 s = f.read() print(s) f.close() """ rt wt 以文本的形式进行读写 """ |
其运行结果与Python 2.X版本代码运行结果一致。
