如何读写文本文件?

需求:
某文本文件编码格式已知(如utf-8,GBK,BIG5),在python2.x和python3.x中分别如何读取该文件?

思路:
明确的一点:
在python2和python3中字符串的语义发生了变化
python2中的 str --> python3中的 bytes
python2中的 unicode --> python3中的str
python2:写入文件前对unicode编码,读入文件后对二进制字符串解码
python3:open函数指定't'的文本样式,encoding指定编码格式

代码:

# python2中

f = open('py2.txt','w')

#unicode字符串:
s = u'你好'

#将unicode字符串写入文本文件中去,注意要先编码才能写入
f.write(s.encode('gbk'))

# 读取文件中的内容
f.open('py2.txt','r')

t = f.read()
# 还原成文本要先进行解码,等到unicode的字符串:
t.decode('gbk')

print t.decode('gbk')

# python3中
# 表示bytes类型的字符串:
b = b'efwjijsx'

# 表示unicode字符串,在python3 中字符串直接就是unicode字符串
s = '你好'

# 在python3中通过指定encoding,省去了python2中手工编码和解码的过程,更加方便

# 写入文件,t可以省略,默认以t(文本)的形式写,实际上写入的也是字节但是自动完成了编码。
f = open('py3.txt','wt',encoding='utf8')
f.write('你好,我爱编程')
f.close

# 读取文件,实际上读取的也是字节但是自动完成了解码。
f = open('py3.txt','rt',encoding='utf8')
s = f.read()
print(s) 

===================================================
py2:
>>> s = u'我是齐天大圣,我爱蟠桃'

>>> type(s)
unicode

>>> f = open('a.txt','w')

>>> f.write(s.encode('utf-8'))

>>> f.flush()

>>> cat a.txt
我是齐天大圣,我爱蟠桃
>>> f = open('a.txt')

>>> txt = f.read()

>>> txt
'\xe6\x88\x91\xe6\x98\xaf\xe9\xbd\x90\xe5\xa4\xa9\xe5\xa4\xa7\xe5\x9c\xa3\xef\xbc\x8c\xe6\x88\x91\xe7\x88\xb1\xe8\x9f\xa0\xe6\xa1\x83'

>>> type(txt)
str

>>> txt.decode('utf-8')
u'\u6211\u662f\u9f50\u5929\u5927\u5723\uff0c\u6211\u7231\u87e0\u6843'

>>> print(txt.decode('utf-8'))
我是齐天大圣,我爱蟠桃

py3:
>>> s = 'abc'

>>> type(s)
str

>>> bin(ord('a'))
'0b1100001'

>>> 2 ** 8
256

>>> u = u'刘'

>>> s = '刘欺罔'

>>> type(s)
str

>>> s = '我是齐天大圣,我爱蟠桃'

>>> type(s)
str

>>> f = open('b.txt','w')

>>> f = open('b.txt','w',encoding='gbk')

>>> f.write(s)
11

>>> f.flush()

>>> cat b.txt
����������ʥ���Ұ�����
>>> f = open('b.txt',encoding='gbk')

>>> f.read()
'我是齐天大圣,我爱蟠桃'

>>> 

posted @ 2020-07-11 17:33  Richardo-M-Lu  阅读(312)  评论(0编辑  收藏  举报