存在空文件
此問題是由於您未能關閉文件描述符而導致的。你有f.close
但它應該是f.close()
(一個函數調用)。最後你還需要一個f2.close()
。
沒有close
它需要一段時間,直到緩衝區的內容到達文件。在不使用文件描述符時儘快關閉文件描述符是一種很好的做法。
作爲一個側面說明,您可以使用下面的語法糖,以保證文件描述符儘快儘可能近:
with open(file, mode) as f:
do_something_with(f)
現在,關於覆蓋部分:
寫入到文件而不會覆蓋以前的內容。
簡短回答:您不以正確的模式打開文件。使用追加模式("a"
)。
龍回答:
這是預期的行爲。閱讀以下內容:
>>> help(open)
Help on built-in function open in module __builtin__:
open(...)
open(name[, mode[, buffering]]) -> file object
Open a file using the file() type, returns a file object. This is the
preferred way to open a file. See file.__doc__ for further information.
>>> print file.__doc__
file(name[, mode[, buffering]]) -> file object
Open a file. The mode can be 'r', 'w' or 'a' for reading (default),
writing or appending. The file will be created if it doesn't exist
when opened for writing or appending; it will be truncated when
opened for writing. Add a 'b' to the mode for binary files.
Add a '+' to the mode to allow simultaneous reading and writing.
If the buffering argument is given, 0 means unbuffered, 1 means line
buffered, and larger numbers specify the buffer size. The preferred way
to open a file is with the builtin open() function.
Add a 'U' to mode to open the file for input with universal newline
support. Any line ending in the input file will be seen as a '\n'
in Python. Also, a file so opened gains the attribute 'newlines';
the value for this attribute is one of None (no newline read yet),
'\r', '\n', '\r\n' or a tuple containing all the newline types seen.
所以,在閱讀手冊顯示,如果你想保持的內容,你應該打開追加模式:
open(file, "a")
您可以打開同一個文件多次。裏面有不同的光標。 –