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

What's the difference between opening a file for update and just appending?

本问题已经有最佳答案,请猛点这里访问。

就像在用open()打开一个文件时,为什么我们有模式'r+'、'w+'、'a+'?当然,模式"A"也有同样的作用吗?我对模式"A"和"A+"之间的区别尤其感到困惑——有人能解释它们的区别在哪里,如果可能的话,什么时候应该使用其中一种模式?


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

BSD Fopen手册页定义如下:

1
2
3
4
5
6
7
8
9
 ``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+允许读取文件。

有关更多信息,请参阅本文。


引用自python 2.7教程:

mode can be 'r' when the file will only be read, 'w' for only writing
(an existing file with the same name will be erased), and 'a' opens
the file for appending; any data written to the file is automatically
added to the end. 'r+' opens the file for both reading and writing.
The mode argument is optional; 'r' will be assumed if it’s omitted.

"a"以写(在文件结尾附加)模式打开文件,而"r+"以读和写(在文件开头插入)模式打开文件。