【发布时间】:2015-10-25 23:21:32
【问题描述】:
在尝试对以 a+ 模式 (Python 3.4.1) 打开的文件调用 read() 时发现一个奇怪的行为
如图所示
File mode for creating+reading+appending+binary
可以在读取/附加模式下打开文件应该。
但是
这段代码:
with open("hgrc", "a+") as hgrc:
contents=hgrc.read()
返回contents={str}''。根据上面发布的答案,这是出乎意料的。
现在,下面的代码
with open("hgrc", "r+") as hgrc:
contents=hgrc.read()
返回contents={str}'contents of hgrc.....',这是预期的,但没有给我们附加到文件的选项。
根据规格
https://docs.python.org/2/library/functions.html#open
Modes 'r+', 'w+' and 'a+' open the file for updating (reading and writing);
note that 'w+' truncates the file. Append 'b' to the mode to open the filein binary mode, on systems that differentiate between binary and textfiles; on systems that don’t have this distinction, adding the 'b' has noeffect.
这意味着
当我们以a+ 模式打开一个文件时,我们应该能够在它上面调用read() 并取回文件的内容,对吗?
想法?意见?等等??
【问题讨论】:
-
看看我的answer here 是否有帮助。它在
C线程上,但它也应该适用 -
这有助于真正记住单击按钮 (;
标签: python file python-3.x file-io