標籤:
1.開啟檔案
open(name[mode[,buffing]) 參數: 檔案,模式,緩衝
1)name: 是強制選項,模式和緩衝是可選的
#如果檔案不在,會報下面錯誤
1 >>> f = open(r‘D:\text.txt‘,‘r‘) 2 Traceback (most recent call last): 3 File "<stdin>", line 1, in <module> 4 IOError: [Errno 2] No such file or directory: ‘D:\\text.txt‘
2)檔案模式
‘r‘ 讀模式‘w‘ 寫入模式’a‘ 追加模式‘b‘ 二進位模式(可添加到其他模式中使用)’+‘ 讀/寫入模式(可添加到其他模組中使用)
NOTE:
預設的方式,比如說open(‘filename‘)是讀模式
r+, 則表示可讀寫
如果是二進位檔案或圖形檔案,則必須用緩衝模式
普通的w模式會覆蓋檔案的內容,a模式則不會.
rb則可以用來讀取二進位檔案.
通過參數模式中使用U參數,能夠在開啟檔案時使用通用的分行符號支援模式,無論\r,\n\r,都會換成\n,而不用考慮啟動並執行平台.
3)緩衝
0或者False: 無緩衝,所有操作直接針對硬碟
1或者True: 有緩衝,記憶體代替硬碟,速度快,只有close,flush才寫入硬碟同步.
> 1 : 表示緩衝區的大小
-1 : 表示預設的緩衝區大小
2.檔案方法
2.1 讀寫
#對空檔案來說: 提供寫時,會在已在字串末尾追加,
1 >>> f = open(‘somefile.txt‘,‘w‘) 2 >>> f.write(‘Hello,‘) 3 >>> f.write(‘World!‘) 4 >>> f.close() 5 #somefile.txt檔案內容 6 Hello,World!
#對於非空檔案:提供w方法時,會覆蓋檔案中的內容
1 >>> f = open(‘somefile‘,‘w‘) 2 >>> f.write(‘This is 1st line.\n‘) 3 >>> f.write(‘This is 2nd line.‘) 4 >>> f.close() 5 #somefile.txt檔案內容 6 This is 1st line. 7 This is 2nd line.
簡單讀取的例子:
1 >>> f = open(‘somefile.txt‘,‘r‘) 2 >>> f.read(16)#先讀取16個字元 3 ‘This is 1st line‘ 4 >>> f.read() #會讀取剩下的內容,除非seek定位到0,重新讀取 5 ‘.\nThis is 2nd line.‘ 6 >>> f.close()
2.2 管道輸出
$ cat somefile.txt | python somescript.py | sort
#一個簡單例子: 統計一個文本中單詞的數量
$ cat somefile.txt This is a book!That is a dog!Who are you?
指令碼清單:
#somescript.py import sys text = sys.stdin.read() #讀取所以輸入words = text.split() #分割字串 print "Word Count:", len(words)
輸出結果:
# cat somefile.txt | python somescript.py Word Count: 11
2.3 讀寫行
readline : 讀取行,包括分行符號readlines: 讀取所有行write: 寫一行, 注意:沒有writeline方法writelines: 寫多行
NOTE: 如何判斷不同的行以什麼結尾? os.linesep
#UNIX >>> import os >>> os.linesep ‘\n‘ #WINDOWS >>> import os >>> os.linesep ‘\r\n‘
2.4 基本檔案方法
#測試文本somefile.txt
Welcome to this fileThere is nothing here exceptThis stupid haiku
#首先讀取指定字元 —— f.read(n)
>>> f = open(r‘d:\Learn\Python\somefile.txt‘) >>> f.read(7) ‘Welcome‘ >>> f.read(4) ‘ to ‘ >>> f.close()
#其次讀取所有的行—— f.read()
>>> f = open(r‘d:\Learn\Python\somefile.txt‘,‘r‘) >>> print f.read() Welcome to this file There is nothing here except This stupid haiku
#接著是讀取行 —— f.readline()
>>> f.close() >>> f = open(r‘d:\Learn\Python\somefile.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.readlines()
>>> import pprint >>> pprint.pprint(open(‘somefile.txt‘).readlines()) [‘Welcome to this file\n‘, ‘There is nothing here except\n‘, ‘This stupid haiku‘]
#下面是寫檔案—— f.write(‘ ......‘)
>>> f = open(r‘somefile.txt‘,‘w‘) >>> f.write(‘this\nis no\nhaiku‘) >>> f.close() 運行檔案後,內容如下: this is no haiku
#最後是writelines—— f.writelines( ‘ ....‘ )
>>> f = open(r‘somefile.txt‘) >>> lines = f.readlines() >>> f.close() >>> lines[1] = "isn‘t a\n" >>> f = open(‘somefile.txt‘,‘w‘) >>> f.writelines(lines) >>> f.close() 運行後,檔案內容如下: this isn‘t a haiku
2.5 關閉檔案
時刻記得close()來關閉檔案,這樣做的目的:
安全考慮,防止檔案因為某些原因崩潰,寫不進資料
出於資料同步考慮,close(),才會往硬碟中寫資料
出於效率的考慮,記憶體中的資料可清空一部分出來
為了確保程式結束時close(),可以用try/finally結合使用
# Open your file here try: # Write data to your file finally: file.close()
NOTE: 一般檔案在close()之後才會寫入硬碟,如果想不執行close()方法,又可以看到寫入的內容,那麼flush就派上用場了.
3.對檔案內容迭代
3.1 按位元組處理
def process(string): print ‘Processing...‘, string f = open(‘somefile.txt‘) while True: char = f.read(1) if not char: break process(char) f.close()
3.2 按行處理
f = open(filename) while True: line = f.readline() if not line: break process(line) f.close()
3.3 讀取所有內容
如果檔案不是很大,可以用read(),或者readlines()讀取的內容作為字串來處理.
#用read來迭代每個字元
f = open(r‘D:\Work\Python\somefile.txt‘) for char in f.read(): process(char) f.close()
#用readlines來迭代行
f = open(r‘D:\Work\Python\somefile.txt‘,‘r‘) for line in f.readlines(): process(line) f.close()
3.4 使用fileinput懶惰型迭代
在需要對一個大檔案進行迭代時,readlines會佔用太多的記憶體。這個時候可以使用while迴圈和readline方法來替代。
import fileinput def process(string): print ‘Processing...‘, string for line in fileinput.input(‘somefile.txt‘): process(line)
3.5 檔案迭代器
#Python中檔案是可以迭代的
f = open(‘somefile.txt‘) for line in f: print line, f.close()
#如果希望Python來完成關閉的動作,對檔案進行迭代,而不使用變數儲存變數,代碼可以更加精簡
for line in open(‘somefile.txt‘): print line,
#sys.stdin也是可以迭代的
import sys for line in sys.stdin: print line, 運行結果: D:\Work\Python>python file.py #輸入下面兩行 Hello,World! Hello,Jerry! ^Z #按下CTRL+Z鍵後,輸入的內容,顯示 Hello,World! Hello,Jerry!
#可以對檔案迭代器執行和普通迭代器相同的操作。比如將它們轉換為字串列表,這樣所達到的效果和使用readlines一樣.
>>> f = open(‘somefile.txt‘,‘w‘) >>> f.write(‘First line\n‘) >>> f.write(‘Second line\n‘) >>> f.write(‘Third line\n‘) >>> f.close() >>> lines = list(open(‘somefile.txt‘)) >>> lines [‘First line\n‘, ‘Second line\n‘, ‘Third line\n‘] >>> first,second,third = open(‘somefile.txt‘) >>> first ‘First line\n‘ >>> second ‘Second line\n‘ >>> third ‘Third line\n‘
python基礎教程總結10——檔案