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.
6 回答
打开模式与C标准库函数 fopen() 完全相同 .
The BSD fopen manpage将它们定义如下:
我注意到,我不时需要Google重新开始,只是为了 Build 模式之间主要差异的心理形象 . 所以,我认为下一次阅读图表会更快 . 也许其他人也会觉得有帮助 .
相同的信息,只是表格形式
含义是:(只是为了避免任何误解)
读取 - 允许从文件读取
写入 - 允许写入文件
create - 如果文件尚不存在,则创建该文件
trunctate - 在打开文件期间,它变为空(文件的所有内容都被删除)
开始时的位置 - 文件打开后,初始位置设置为文件的开头
结束位置 - 文件打开后,初始位置设置为文件末尾
注意:
a
和a+
总是附加到文件末尾 - 忽略任何seek
动作 .BTW . 对于在
a+
模式下打开的新文件,至少在我的win7 / python2.7上有趣的行为:write('aa'); seek(0, 0); read(1); write('b')
- 第二个write
被忽略write('aa'); seek(0, 0); read(2); write('b')
- 第二次write
加注IOError
选项与C标准库中的fopen function相同:
w
截断文件,覆盖已有的文件a
附加到文件,添加到已存在的任何内容w+
打开以进行读写,截断文件但还允许您回读已写入文件的内容a+
打开以进行追加和读取,允许您同时附加到文件并读取其内容我试图弄清楚为什么你会使用模式'w'而不是'w' . 最后,我做了一些测试 . 我没有看到模式'w'的目的太多,因为在这两种情况下,文件都被截断为开头 . 然而,有了'w',你可以在写完之后回头看 . 如果您尝试使用'w'进行任何读取,则会引发IOError . 不使用带有'w'模式的搜索进行读取不会产生任何结果,因为文件指针将位于您编写的位置之后 .
我认为这对跨平台执行很重要,即作为CYA . :)
这直接引自Python Software Foundation 2.7.x .