为什么在我停止程序之前不会写入文件? [英] How come a file doesn't get written until I stop the program?

查看:29
本文介绍了为什么在我停止程序之前不会写入文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行一个测试,发现在我用 control-C 中止程序之前,文件实际上并没有被写入.谁能解释为什么会发生这种情况?

I'm running a test, and found that the file doesn't actually get written until I control-C to abort the program. Can anyone explain why that would happen?

我希望它同时写入,所以我可以在这个过程中读取文件.

I expected it to write at the same time, so I could read the file in the middle of the process.

import os
from time import sleep

f = open("log.txt", "a+")
i = 0
while True:
  f.write(str(i))
  f.write("
")
  i += 1
  sleep(0.1)

推荐答案

写入磁盘很慢,因此许多程序将写入存储到它们一次写入的大块中.这称为缓冲,当您打开文件时,Python 会自动执行此操作.

Writing to disk is slow, so many programs store up writes into large chunks which they write all-at-once. This is called buffering, and Python does it automatically when you open a file.

当您写入文件时,您实际上是在写入内存中的缓冲区".当它填满时,Python 会自动将其写入磁盘.你可以用

When you write to the file, you're actually writing to a "buffer" in memory. When it fills up, Python will automatically write it to disk. You can tell it "write everything in the buffer to disk now" with

f.flush()

这还不是全部,因为操作系统可能也会缓冲写入.你可以告诉it

This isn't quite the whole story, because the operating system will probably buffer writes as well. You can tell it to write the buffer of the file with

os.fsync(f.fileno())

最后,你可以告诉 Python 不要用 open(f, "w", 0) 缓冲一个特定的文件,或者只用 open(f,"w", 1).自然,这会减慢对该文件的所有操作,因为写入速度很慢.

Finally, you can tell Python not to buffer a particular file with open(f, "w", 0) or only to keep a 1-line buffer with open(f,"w", 1). Naturally, this will slow down all operations on that file, because writes are slow.

这篇关于为什么在我停止程序之前不会写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆