1.打開/關閉文件python
首先來看一下Python中的open函數:緩存
open(file, mode='r', buffering=-1, encoding=None)函數
1)file: 文件名編碼
2)mode: 這個跟標準c庫中fopen中的mode參數取值相似:spa
'r': 以只讀方式打開文件,若是文件不存在,則會拋出IOErrorcode
‘w': 以只寫方式打開文件,若是文件不存在,則會自動建立文件;若是文件已經存在,則會清空文件已有的內容內存
'a': 以追加的方式打開,通常會與'w'聯合使用;utf-8
'b': 二進制模式打開,表示此文件中的數據不是文本數據;it
'+': 讀/寫模式, 'r+':表示讀寫方式打開文件,'w+'以讀寫方式打開文件;for循環
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: break except IOError: print('file IOError') finally: f.close() >>> hello Python hello world
在上面的代碼中,咱們發現每次都要在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 object with open('data.txt') as f: for line in f: print(line)
執行後的輸出與上面同樣,可是代碼顯得更加的簡潔。
file object還有seek, trunscate, flush等方法,這些方法都是跟c標準庫中的方法對應的。