Python的open函數定義了哪些屬性?關閉和讀寫對應的應該如何使用?

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章