在 Python 中 close() 是否意味着 flush() ?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2447143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:40:27  来源:igfitidea点击:

does close() imply flush() in Python?

pythonoperating-systemflush

提问by Adam Matan

In Python, and in general - does a close()operation on a file object imply a flush()operation?

在 Python 中,一般来说 -close()对文件对象的flush()操作是否意味着操作?

采纳答案by Martin Wickman

Yes. It uses the underlying close()function which does that for you (source).

是的。它使用close()为您执行此操作的底层函数(source)。

回答by Douglas Leeder

NB: close()and flush()won't ensure that the data is actually secure on the disk. It just ensures that the OS has the data == that it isn't buffered inside the process.

注意:close()并且flush()不会确保磁盘上的数据实际上是安全的。它只是确保操作系统拥有数据 == 没有在进程内缓冲。

You can try sync or fsync to get the data written to the disk.

您可以尝试同步或 fsync 来获取写入磁盘的数据。

回答by Felix D.

Yes, in Python 3 this is finally in the official documentation, but is was already the case in Python 2 (see Martin's answer).

是的,在 Python 3 中,这最终出现在官方文档中,但在 Python 2 中已经是这种情况(参见Martin 的回答)。

回答by przemek

filehandle.close does not necessarily flush. Surprisingly, filehandle.flush doesn't help either---it still can get stuck in the OS buffers when Python is running. Observe this session where I wrote to a file, closed it and Ctrl-Z to the shell command prompt and examined the file:

filehandle.close 不一定刷新。令人惊讶的是,filehandle.flush 也无济于事——当 Python 运行时,它仍然会卡在操作系统缓冲区中。观察我写入文件的会话,关闭它并按 Ctrl-Z 到 shell 命令提示符并检查文件:

$  cat xyz
ghi
$ fg
python

>>> x=open("xyz","a")
>>> x.write("morestuff\n")
>>> x.write("morestuff\n")
>>> x.write("morestuff\n")
>>> x.flush
<built-in method flush of file object at 0x7f58e0044660>
>>> x.close
<built-in method close of file object at 0x7f58e0044660>
>>> 
[1]+  Stopped                 python
$ cat xyz
ghi

Subsequently I can reopen the file, and that necessarily syncs the file (because, in this case, I open it in the append mode). As the others have said, the sync syscall (available from the os package) should flush all buffers to disk but it has possible system-wide performance implications (it syncs all files on the system).

随后我可以重新打开文件,这必然会同步文件(因为,在这种情况下,我以追加模式打开它)。正如其他人所说,同步系统调用(可从 os 包获得)应该将所有缓冲区刷新到磁盘,但它可能会影响系统范围的性能(它同步系统上的所有文件)。