Python open()追加和读取,file.read()返回空字符串 [英] Python open() append and read, file.read() returns empty string

查看:332
本文介绍了Python open()追加和读取,file.read()返回空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试以a+模式(Python 3.4.1)打开的文件上调用read()时,发现了奇怪的行为

Noticed an odd behavior when attempting to call read() on a file opened in a+ mode (Python 3.4.1)

如此处所示
用于创建+ reading + appending + binary的文件模式
可以在假定为的读/追加模式下打开文件.

As seen here
File mode for creating+reading+appending+binary
It's possible to open a file in read/append mode supposedly.

但是
这段代码:

However
This code:

with open("hgrc", "a+") as hgrc:
            contents=hgrc.read()

返回contents={str}''.根据上面发布的答案,这是意外的.
现在,以下代码

returns contents={str}''. Which is unexpected based upon the answer posted above.
Now, the following code

with open("hgrc", "r+") as hgrc:
            contents=hgrc.read()

返回contents={str}'contents of hgrc.....',这是预期的,但没有给我们提供附加到文件的选项.

returns contents={str}'contents of hgrc.....', which is expected, but doesn't give us the option to append to the file.

根据规范

https://docs.python.org/2/library/functions.html#打开

According to the specs

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()并将文件的内容取回来,对吗? 有什么想法吗?意见?等等?

Which means
When we open a file in a+ mode, we should be able to call read() on it and get the contents of the file back, correct? Thoughts? Opinions? Etc??

推荐答案

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

a+ opens the file at the end for appending. You need to call .seek(0) on it if you want to then read in its contents, but at that point you might as well just use r+, because that opens the file at the start.

这篇关于Python open()追加和读取,file.read()返回空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆