19. 读写文本文件

2021/4/25 10:25:35

本文主要是介绍19. 读写文本文件,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

在Python 2.x和Python 3.x中,字符串的语义发生了变化:

Python2Python3
strbytes
unicodestr

要求:某文本文件编码格式已知(如 UTF-8,GBK,BIG5),在Python 2.x和Python 3.x 中分别读写该文件。

Python 2.x:写入文件前对unicode编码,读入文件后对字节进行解码。

Python 3.x:open()函数默认指定t以文本模式,endcoding指定编码格式。


  • Python 2.x写入文件:
>>> s = u'我爱Python'>>> type(s)<type 'unicode'>>>> f = open('a.txt', 'w')>>> f.write(s.encode('utf8'))               #uft-8编码>>> f.flush()

# cat a.txt我爱Python

  • Python 2.x读取文件:
>>> f = open('a.txt', 'r')>>> txt = f.read()>>> type(txt)<type 'str'>>>> txt'\xe6\x88\x91\xe7\x88\xb1Python'>>> txt.decode('utf8')              #utf-8解码u'\u6211\u7231Python'>>> print txt.decode('utf8')我爱Python


  • Python 3.x写入文件:
>>> s = '我爱Pyhon'>>> type(s)<class 'str'>>>> f = open('b.txt', 'w', encoding='gbk')              #默认以文本模式打开,'wt'可省略为'w';默认encoding='utf8'>>> f.write(s)7>>> f.flush()

  • Python 3.x读取文件:
>>> f = open('b.txt', 'r', encoding='gbk')>>> f.read()'我爱Pyhon'




这篇关于19. 读写文本文件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程