And*_*ley 4 python file-io file python-3.x
尝试调用read()以a+模式打开的文件时注意到奇怪的行为(Python 3.4.1)
如此处所示
用于创建+读取+附加+二进制
的文件模式可以在读取/附加模式下打开文件.
但是
这段代码:
with open("hgrc", "a+") as hgrc:
contents=hgrc.read()
Run Code Online (Sandbox Code Playgroud)
回报contents={str}''.根据上面发布的答案,这是出乎意料的.
现在,以下代码
with open("hgrc", "r+") as hgrc:
contents=hgrc.read()
Run Code Online (Sandbox Code Playgroud)
返回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()它并获取文件的内容,对吗?思考?意见?等等??
这是Python 2 vs.Python 3问题。
open()a+在两个Python版本中,的行为有所不同。(注意:您显示使用的是Python 3.4.1,但您引用的是Python 2的文档!)
(实际上,您要查找的行为(“ 表示 ”中的含义)可以在Python 2中正常工作。我认为它们已更改了该行为,因为“ append”对许多人来说意味着“文件末尾的文件指针”。)
$ python3
Python 3.4.3 (default, Jul 28 2015, 18:20:59)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> lic = open('LICENSE', 'a+')
>>> lic.read()
''
>>> # Hmmm, no content? EOF, obviously. Let's reset the file pointer ...
>>> lic.seek(0)
0
>>> lic.read()
'Apache License\nVersion 2.0, January 2004\n...'
Run Code Online (Sandbox Code Playgroud)
$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> lic = open('LICENSE', 'a+')
>>> lic.read()
'Apache License\nVersion 2.0, January 2004\n...'
>>> lic.seek(0)
>>> lic.read()
'Apache License\nVersion 2.0, January 2004\n...'
Run Code Online (Sandbox Code Playgroud)
结束语:使用,无论使用哪个Python版本,在打开文件后seek(0) 始终使用Always是安全的a+。这似乎是特定于该a+模式的。
有人会认为文件操作是系统调用,因此由操作系统处理。这与Python不同,因为根据Python文档,它看起来像:
注意: Python不依赖于底层操作系统的文本文件概念;所有处理均由Python本身完成,因此与平台无关。
顺便说一句,此行为已报告为 Python错误跟踪器上的错误。