-1

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

4

2 回答 2

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+ 允许读取文件。

有关更多信息,请参阅此帖子

于 2013-08-15T15:03:30.170 回答
0

引用自 Python 2.7 教程:

mode 可以是 'r' 只读取文件,'w' 只写入(同名的现有文件将被删除),'a' 打开文件进行追加;写入文件的任何数据都会自动添加到末尾。'r+' 打开文件进行读写。mode 参数是可选的;如果省略,将假定 'r'。

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

于 2013-08-15T15:03:59.227 回答