open檔案操作之mode模式剖析,openmode模式剖析
Python可以使用open函數來實現檔案的開啟,關閉,讀寫操作;
Python3中的open函數定義為:
open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
其中mode列表為:
'r' #open for reading (default)'w' #open for writing, truncating the file first'x' #create a new file and open it for writing,python3新增'a' #open for writing, appending to the end of the file if it exists'b' #binary mode't' #text mode (default),python3新增'+' #open a disk file for updating (reading and writing)'U' #universal newline mode (deprecated)
這裡我們主要關心一下'r', 'w', 'a', 'r+', 'w+', 'a+', 'x',很多人容易混淆不同模式的讀寫操作
1)'r'
唯讀模式,open函數中mode參數的預設模式,檔案不存在的話,報FileNotFoundError(python2是IOError);
檔案開啟後,初始遊標位置為0;
每次讀都是從遊標位置開始讀;
如果進行了寫操作,會報如下異常:
io.UnsupportedOperation: not writable
2)'w'
唯寫模式,檔案不存在的話,建立檔案;檔案存在的話,首先清空檔案,然後開始寫;
檔案開啟後,初始遊標位置為0;
每次寫都是從遊標位置開始寫;
如果進行了讀操作,首先檔案也會被清空,會報如下異常:
io.UnsupportedOperation: not readable
3)‘a’
追加模式,檔案不存在話,建立檔案;檔案存在的話,不會清空檔案;
檔案開啟後,初始遊標位置為檔案結尾;
每次寫都是從結尾開始寫;
如果進行了讀操作,同時報如下異常:
io.UnsupportedOperation: not readable
上面的比較好理解,下面就有點繞了
4)'r+'
讀寫入模式,檔案不存在的話,報FileNotFoundError(python2是IOError);
檔案開啟後,初始遊標位置為0;
每次讀寫都是從遊標位置開始;但是對於寫操作,類似於替換操作;
看如下代碼:
檔案內容為:
abcdefg
代碼內容為:
f = open('open_mode.txt', 'r+')f.write('xyz')f.close()
運行代碼後,檔案內容變為:
xyzdefg
5)'w+'
唯寫模式,檔案不存在的話,建立檔案;檔案存在的話,首先清空檔案;
檔案開啟後,初始遊標位置為0;
每次讀寫都是從遊標位置開始;寫操作,類似於替換操作;
6)‘a+’
追加模式,檔案不存在話,建立檔案;檔案存在的話,不會清空檔案;
檔案開啟後,初始遊標位置為檔案結尾;
每次寫都是從結尾開始寫;
讀操作從遊標位置開始;
7) 'x'
python3新加
建立檔案並寫操作,操作必須是不存在的檔案,如果操作的檔案已存在,則報錯FileExistsError
不可讀,如果進行了讀操作,同時報如下異常:
io.UnsupportedOperation: not readable
最後畫一張表格總結一下:
open的內容還有很多,針對於讀,還有個更好的模組linecache用於讀取大檔案;以後有時間繼續擴充