![](/img/trans.png)
[英]Why does changing to `w+` mode for simultaneous reading from and writing to a file cause the read to fail?
[英]Why does the python file descriptor 'w+' erase the contents of file when used for reading?
foo.txt
內容
Hello World!
兩個functions
:
def read1(file):
with open(file, 'r+') as fp:
print fp.read()
def read2(file):
with open(file, 'w+') as fp:
print fp.read()
函數read1('foo.txt')
輸出: Hello World!
函數read2('foo.txt')
輸出:
它基本上什么也不輸出。 但為什么?
不僅如此, foo.txt
的內容也已被刪除。
我認為w+
意味着您截斷了文件,這意味着您將其覆蓋。 但是我什fp.write()
沒有使用fp.write()
。
“截斷文件”並不意味着覆蓋現有內容(而是保留該內容直到被覆蓋); 相反,它意味着完全刪除文件被截斷后的所有內容。 在這種情況下,這就是文件的開頭。
如果要打開文件並能夠在對任何子集執行就地寫入之前讀取現有內容,則r+
是合適的模式。
引用WordNet 3.0中“截斷”的定義來“截斷”某些內容是為了將其截斷或縮短:
截短
3:通過剪短使其變短; “刪減一個詞”; “侵蝕把山的山脊截斷了” [syn:截短,剪短]
因此,該名稱與當前的行為非常匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.