python打开内置函数:模式a,a +,w,w +和r +之间的区别?

在python内置的open函数中,w,a,w +,a +和r +之间的确切区别是什么?

特别是,文件意味着所有这些将允许写入文件,并说它打开“附加”,“写”和“更新”具体的文件,但没有定义这些术语的含义。

开放模式是完全一样的C fopen() std库函数。

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. 

我注意到,有时我需要谷歌再一次打开,只是为了build立模式之间的主要区别的心理形象。 所以,我认为下一次阅读图表会更快。 也许别人也会觉得有帮助。

相同的信息,只是表格forms

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

意思是:(只是为了避免任何误解)

  • 读 – 从文件读取是允许的
  • 写 – 写入文件是允许的

  • 创build – 如果文件不存在,则创build文件

  • trunctate – 在打开文件的时候它是空的(文件的所有内容都被删除)

  • 开始位置 – 文件打开后,初始位置设置为文件的开始位置

  • 结束位置 – 打开文件后,初始位置设置为文件结尾

注意: aa+总是追加到文件末尾 – 忽略任何seek动作。
BTW。 有趣的行为,至less在我的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

选项与C标准库中的fopen函数相同:

w截断文件,覆盖已经存在的文件

附加到文件,添加到已有的东西

w+打开读取和写入,截断文件,但也允许您回读写入文件的内容

打开a+以进行追加和读取,允许您追加到文件并读取其内容

我试图找出为什么你会使用模式“W +”与“W”。 最后,我做了一些testing。 我没有看到模式'w +'有太多目的,因为在这两种情况下,文件都被截断。 然而,用“w +”,你可以通过回写来阅读。 如果你用'w'来读取任何数据,就会抛出一个IOError。 因为文件指针会在你写的地方之后,所以在不使用模式'w +'寻找的情况下不会产生任何东西。

我认为这是跨平台执行考虑的重要因素,也就是CYA。 🙂

在Windows上,附加到模式的“b”以二进制模式打开文件,所以也有像“rb”,“wb”和“r + b”这样的模式。 Windows上的Python区分文本和二进制文件; 数据读取或写入时,文本文件中的行尾字符会自动稍微改变。 这种对文件数据的后台修改对于ASCII文本文件来说是很好的,但是它会像JPEG或者EXE文件那样破坏二进制数据。 读取和写入这些文件时要非常小心地使用二进制模式。 在Unix上,在模式中附加一个'b'并不会造成什么影响,所以你可以在所有的二进制文件中使用它。

这是从Python软件基金会2.7.x直接引用的。