同樣是《python基礎教程(第二版)》的內容,只是后面內容學起來,相比前面會比較有趣,也更加實用,所以,將“基礎”改為“進階”。
python 電子書分享地址:http://yunpan.cn/Q2U87uGrNiTA3
本節講文件的操作
-------------------------------
打開文件
open函數用來打開文件,語法如下:
open(name[, mode[,buffering]])
open函數使用一個文件名作為唯一的強制參數,然后返回一個文件對象。假設我要打開我硬盤(I:/python/test.txt) 文件,可以用下面方法:
>>> f = open(r'i:\python\test.txt')
open函數中模式參數的常用值

基本文件方法
打開文件是第一步,下面就需要對文件進行讀或寫,可以write 和 read方法進行讀或寫。
#寫入文件內容 >>> f = open('test.txt','w') >>> f.write('hello,') >>> f.write('world!') >>> f.close() # 讀取文件內容 >>> f = open('test.txt','r') >>> f.read(4) #讀取前4個字符 'hell' >>> f.read() #讀取剩余的所有字符 'o,world!'
關閉文件
應該牢記使用close方法關閉文件。盡管一個文件對象在退出程序后會自動關閉,但關閉文件是沒什么害處的,可以避免在某些操作系統或設置中進行無用的修改,這樣做也會避免用完系統中打開文件的配額。
使用基本文件方法
假如test.txt文件包含如下內容:
-----------------------------
Welcome to this file
There is nothing here except
This stupid haiku
-----------------------------
下面是基本讀文件的方法:
# read(n) 指定參數 >>> f = open(r'I:\python\test.txt') >>> f.read(7) 'Welcome' >>> f.read(4) ' to ' >>> f.close() # read() 不指定參數 >>> f = open(r'I:\python\test.txt') >>> print f.read() Welcome to this file There is nothing here except This stupid haiku >>> f.close() # readline() >>> f = open(r'I:\python\test.txt') >>> for i in range(3): print str(i) + ':' + f.readline() 0:Welcome to this file 1:There is nothing here except 2:This stupid haiku >>> f.close() #readlines() >>> import pprint >>> pprint.pprint(open(r'I:\python\test.txt').readlines()) ['Welcome to this file\n', 'There is nothing here except\n', 'This stupid haiku']
readline返回一行的字符串, readlines返回包含文件所有內容的字符串列表, 每個元素是一行的字符串。
pprint 模塊的pprint方法將內容分成每個小項單行顯示。
下面是寫文件的基本方法:
>>> f = open(r'I:\python\test.txt','w') #默認是讀文件,可以不加‘r’,寫文件一定要加’w’ >>> f.write('this\nis no \nhaiku') >>> f.close()

>>> f = open(r'I:\python\test.txt') >>> lines = f.readlines() >>> lines[1] = "isn't a\n" >>> f = open(r'I:\python\test.txt','w') >>> f.writelines(lines) >>> f.close()

對文件內容進行迭代
1、接字節處理
最常見的對文件內容進行迭代的方法是while循環中使用read方法。例如,對每個字符進行循環,可以用下面方法實現:
f = open(filename) char = f.read(1) while char: process(char) char = f.read(1) f.close()
read方法返回的字符串會包含一個字符,直到文件末尾,read返回一個空的字符串,char將變為假。
可以看到,char = f.read(1) 被重復地使用,代碼重復通過被認為是一件壞事,看看下面的方法:
f = open(filename) while True: char = f.read(1) if not char: break process(char) f.close()
這里break語句被頻繁的使用(這樣會讓代碼比較難懂),盡管如此,但它仍然要比前面的方法好。
2、讀取所有內容
如果文件不是很大,那么可以使用不帶參數的read方法一次讀取整個文件,或者使用readlines方法。
#用read迭代每個字符 f = open(filename) for char in f.read(): process(char) f.close()
#用readlines迭代行: f = open(filename) for line in f.readlines(): process(line) f.close()
3、用fileinput 來進行迭代
fileinput模塊包含了打開文件的函數,,只需要傳一個文件名給它
import fileinput for line in fileinput.input(filename): process(line)
4、文件迭代器
好吧!這是python2.2之后才有的方法,如果它一開始就有,上面的方法也許就不存在了。文件對象是可以迭代的,這就意味著可以直接在for循環中對他們進行迭代
f = open(filename) for line in f: process(line) f.close()
再來看下面例子:
>>> f = open(r'I:\python\test.txt','w') >>> f.write('First line\n') >>> f.write('Second line\n') >>> f.write('Third line\n') >>> f.close() >>> lines = list(open(r'I:\python\test.txt')) >>> lines ['First line\n', 'Second line\n', 'Third line\n'] >>> first,second,third = open(r'I:\python\test.txt') >>> first 'First line\n' >>> second 'Second line\n' >>> third 'Third line\n'
在這個例子中:
- 使用序列來對一個打開的文件進行解包操作,把每行都放入一個單獨的變理中,這么做是很有實用性的,因為一般不知道文件中有多少行,但它演示的文件的“迭代性”。
- 在寫文件后一定要關閉文件,這樣才能確保數據被更新到硬盤。