標籤:
1.開啟/關閉檔案
首先來看一下Python中的open函數:
open(file, mode=‘r‘, buffering=-1, encoding=None)
1)file: 檔案名稱
2)mode: 這個跟標準c庫中fopen中的mode參數取值類似:
‘r‘: 以唯讀方式開啟檔案,如果檔案不存在,則會拋出IOError
‘w‘: 以唯寫方式開啟檔案,如果檔案不存在,則會自動建立檔案;如果檔案已經存在,則會清空檔案已有的內容
‘a‘: 以追加的方式開啟,一般會與‘w‘聯合使用;
‘b‘: 二進位模式開啟,表示此檔案中的資料不是文本資料;
‘+‘: 讀/寫入模式, ‘r+‘:表示讀寫方式開啟檔案,‘w+‘以讀寫方式開啟檔案;
4)buffering: 表示是否使用緩衝,如果使用緩衝的話,我們往檔案中寫入資料時,並不會馬上寫入到檔案中,而是寫入到緩衝中,直至我們flush()或者close()時,才會把緩衝中的資料寫入到檔案中;
5)encoding: 指定寫入字元的編碼,如utf-8
open函數如果成功,則會返回一個file object,否則返回None.
關閉檔案: close()函數
f = open(file=‘data.txt‘, mode=‘w+‘, encoding=‘utf-8‘)if f: print(‘open %s success‘ % f.name) f.close()else: print(‘open failed‘)>>>open data.txt success
2.讀寫檔案
在open成功後,會返回一個file object,檔案的讀寫函數,就是調用file object中的讀寫函數來完成的。
1)write(str): 把str寫入到檔案中
2)writelines(seq): 把序列中的每一個元素依次寫入到檔案中,注意每個元素直接並不會自動插入分行符號file.linesep
3)read(): 返回整個檔案的資料
4)readline(): 返迴文件中的一行資料
5)readlines(): 以list的方式返迴文件中的每一行資料,注意每一行的分行符號並沒有去除
6)read(nums): 讀取指定nums個字元
當已讀取到EOF時,會返回None。
#寫入檔案f = open(file=‘data.txt‘, mode=‘w‘, encoding=‘utf-8‘)if f: print(‘open %s success‘ % f.name) f.write(‘hello Python\n‘) lines = (‘hello\n‘, ‘world‘) f.writelines(lines) f.close()else: print(‘open failed‘)
#讀取檔案try: f = open(‘data.txt‘) print(f.readlines())except IOError: print(‘file IOError‘)finally: f.close()>>>[‘hello Python\n‘, ‘hello\n‘, ‘world‘]
如果檔案比較大,調用read()或者readlines()一次性把所有的資料讀取到記憶體中,會佔用較大的內容空間,所以一般的建議是一部分一部分的讀取:
#迴圈讀取並處理try: f = open(‘data.txt‘) while True: line = f.readline() if line: print(line) else: breakexcept IOError: print(‘file IOError‘)finally: f.close()>>>hello Pythonhelloworld
在上面的代碼中,我們發現每次都要在finally中加入f.close(),比較麻煩,所以Python在2.5之後,引入with語句:可以自動協助我們在語句結束後關閉檔案,即使是異常引起的結束:
with open(‘data.txt‘) as f: while True: line = f.readline() if line: print(line) else: break
3.檔案迭代器
在Python2.2開始,file object是可以迭代的,這意味著可以直接在for迴圈中使用。
#iteraing file objectwith open(‘data.txt‘) as f: for line in f: print(line)
執行後的輸出與上面一樣,但是代碼顯得更加的簡潔。
file object還有seek, trunscate, flush等方法,這些方法都是跟c標準庫中的方法對應的。
Python入門(十三) 檔案操作