在python内置的open函数中,模式w
, a
, w+
, a+
和r+
的确切区别是什么? python
特别地,文档暗示全部这些都将容许写入文件,并说它打开文件专门用于“追加”,“写入”和“更新”,但未定义这些术语的含义。 python2.7
打开模式与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.
这些选项与C标准库中的fopen函数相同: 测试
w
截断文件,覆盖已存在的文件 spa
文件a
追加,添加到已经存在的任何内容上 指针
w+
打开以进行读取和写入,截断文件,但也容许您回读已写入文件的内容 code
a+
打开以进行追加和读取,使您既能够追加到文件,也能够读取其内容 文档
我碰巧试图弄清楚为何要使用模式“ w +”与“ w”。 最后,我只是作了一些测试。 我看不到'w +'模式有什么用,由于在两种状况下,文件都是从头开始被截断的。 可是,有了“ w +”,您能够在写完后经过回头阅读。 若是您尝试使用“ w”进行任何读取,都会引起IOError。 在模式“ w +”下不使用seek进行读取不会产生任何结果,由于文件指针将位于您写入的位置以后。 get
我注意到,我不时须要从新打开Google,只是为了构想两种模式之间的主要区别是什么。 所以,我认为下一次阅读图会更快。 也许其余人也会发现它也有帮助。
相同信息,只是表格形式
| r r+ w w+ a a+ ------------------|-------------------------- read | + + + + write | + + + + + write after seek | + + + create | + + + + truncate | + + position at start | + + + + position at end | + +
意义在哪里:(为避免任何误解)
写-容许写入文件
create-若是尚不存在则建立文件
截断-在打开文件期间将其清空(删除了文件的全部内容)
开始位置-打开文件后,初始位置设置为文件的开始
注意: a
和a+
始终附加在文件末尾-忽略任何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