打开文件进行更新和只是附加有什么区别?

时间:2013-08-15 15:00:27

标签: python file-io append

在使用open()打开文件时,为什么我们有模式'r +','w +','a +'?肯定模式'a'做同样的工作?我对模式'a'和'a +'之间的区别感到特别困惑 - 有人可以解释它们的不同之处,如果可能的话,应该使用其中一个或哪一个?

2 个答案:

答案 0 :(得分:3)

打开模式与C fopen()std库函数完全相同。

BSD fopen联机帮助页定义如下:

 ``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.

a和a +之间的唯一区别是a +允许读取文件。

有关详细信息,请参阅this post

答案 1 :(得分:0)

引自Python 2.7教程:

  当只读文件时,

模式可以是'r','w'只能写入   (将删除具有相同名称的现有文件),并打开“a”   附加文件;写入文件的任何数据都是自动的   添加到最后。 'r +'打开文件进行读写。   mode参数是可选的;如果省略,则会假设'r'。

'a'以写入方式打开文件(追加文件末尾)模式,而'r +'以读写方式打开文件(在文件开头插入)。