open檔案操作之mode模式剖析,openmode模式剖析

來源:互聯網
上載者:User

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用於讀取大檔案;以後有時間繼續擴充

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.