[英]Python open() append and read, file.read() returns empty string
嘗試對以a+
模式打開的文件調用read()
時注意到一個奇怪的行為(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
in binary mode, on systems that differentiate between binary and text
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
note that 'w+' truncates the file. Append 'b' to the mode to open the file
files; on systems that don't have this distinction, adding the 'b' has no
files; on systems that don't have this distinction, adding the 'b' has no
effect.
意思是
當我們以a+
模式打開文件時,我們應該能夠對其調用read()
並取回文件的內容,對嗎? 想法? 意見? 等等??
這是 Python 2 與 Python 3 的問題。
open()
with a+
在兩個 Python 版本中的行為不同。 (注意:您透露您使用的是 Python 3.4.1 ,但您引用的是 Python 2的文檔!)
(實際上,您正在尋找的行為(在“這意味着”中)在 Python 2 中按預期工作。我認為他們改變了行為,因為“追加”對許多人來說意味着“文件末尾的文件指針”。)
$ 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...'
$ 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...'
結論:在使用a+
打開文件后始終使用seek(0)
是安全的,無論您使用哪個 Python 版本。 這似乎是特定於a+
模式的。
有人會認為文件操作是一種系統調用,因此它由操作系統處理。 這與 Python 不同,它根據Python 文檔顯示:
注意: Python 不依賴於底層操作系統的文本文件概念; 所有處理都由 Python 本身完成,因此與平台無關。
順便說一句,此行為已被報告為Python 錯誤跟蹤器上的錯誤。
a+
在末尾打開文件以進行追加。 如果您想讀取其內容,則需要對其調用.seek(0)
,但此時您最好只使用r+
,因為這會在開始時打開文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.