python打開內置函數:模式a,a +,w,w +和r +之間的區別?

在python內置的open函數中,模式waw+a+r+的確切區別是什麼? python

特別地,文檔暗示全部這些都將容許寫入文件,並說它打開文件專門用於「追加」,「寫入」和「更新」,但未定義這些術語的含義。 python2.7


#1樓

打開模式與C標準庫函數fopen()徹底相同。 ide

BSD fopen聯機幫助頁對它們的定義以下: 函數

The argument mode points to a string beginning with one of the following
 sequences (Additional characters may follow these sequences.):

 ``r''   Open text file for reading.  The stream is positioned at the
         beginning of the file.

 ``r+''  Open for reading and writing.  The stream is positioned at the
         beginning of the file.

 ``w''   Truncate file to zero length or create text file for writing.
         The stream is positioned at the beginning of the file.

 ``w+''  Open for reading and writing.  The file is created if it does not
         exist, otherwise it is truncated.  The stream is positioned at
         the beginning of the file.

 ``a''   Open for writing.  The file is created if it does not exist.  The
         stream is positioned at the end of the file.  Subsequent writes
         to the file will always end up at the then current end of file,
         irrespective of any intervening fseek(3) or similar.

 ``a+''  Open for reading and writing.  The file is created if it does not
         exist.  The stream is positioned at the end of the file.  Subse-
         quent writes to the file will always end up at the then current
         end of file, irrespective of any intervening fseek(3) or similar.

#2樓

這些選項與C標準庫中的fopen函數相同: 測試

w截斷文件,覆蓋已存在的文件 spa

文件a追加,添加到已經存在的任何內容上 指針

w+打開以進行讀取和寫入,截斷文件,但也容許您回讀已寫入文件的內容 code

a+打開以進行追加和讀取,使您既能夠追加到文件,也能夠讀取其內容 文檔


#3樓

我碰巧試圖弄清楚爲何要使用模式「 w +」與「 w」。 最後,我只是作了一些測試。 我看不到'w +'模式有什麼用,由於在兩種狀況下,文件都是從頭開始被截斷的。 可是,有了「 w +」,您能夠在寫完後經過回頭閱讀。 若是您嘗試使用「 w」進行任何讀取,都會引起IOError。 在模式「 w +」下不使用seek進行讀取不會產生任何結果,由於文件指針將位於您寫入的位置以後。 get


#4樓

我注意到,我不時須要從新打開Goog​​le,只是爲了構想兩種模式之間的主要區別是什麼。 所以,我認爲下一次閱讀圖會更快。 也許其餘人也會發現它也有幫助。


#5樓

相同信息,只是表格形式

| r   r+   w   w+   a   a+
------------------|--------------------------
read              | +   +        +        +
write             |     +    +   +    +   +
write after seek  |     +    +   +
create            |          +   +    +   +
truncate          |          +   +
position at start | +   +    +   +
position at end   |                   +   +

意義在哪裏:(爲避免任何誤解)

  • 讀取-容許從文件讀取
  • 寫-容許寫入文件

  • create-若是尚不存在則建立文件

  • 截斷-在打開文件期間將其清空(刪除了文件的全部內容)

  • 開始位置-打開文件後,初始位置設置爲文件的開始

  • 末尾位置-打開文件後,將初始位置設置爲文件末尾

注意: aa+始終附加在文件末尾-忽略任何seek運動。
順便說一句。 至少在個人win7 / python2.7上,對於以a+模式打開的新文件而言,有趣的行爲是:
write('aa'); seek(0, 0); read(1); write('b') write('aa'); seek(0, 0); read(1); write('b') -第二次write被忽略
write('aa'); seek(0, 0); read(2); write('b') write('aa'); seek(0, 0); read(2); write('b') -第二次write引起IOError

相關文章
相關標籤/搜索