Python open()追加和读取,file.read()返回空字符串


问题内容

尝试调用read()a+模式(Python 3.4.1)打开的文件时,发现异常行为

如此处所示,
用于创建+读取+附加+二进制
的文件模式 可以 按读/附加模式打开文件。

但是
此代码:

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 file
in binary mode, on systems that differentiate between binary and text
files; on systems that don’t have this distinction, adding the 'b' has no
effect.

这意味着
当我们在a+模式下打开文件时,应该可以调用read()它并取回文件的内容,对吗?有什么想法吗?意见?等等??


问题答案:

a+最后打开文件进行追加。.seek(0)如果要阅读其内容,则需要对其进行调用,但是此时您最好只使用r+,因为这会在开始时打开文件。