直到停止程序,文件才被写入? [英] How come a file doesn't get written until I stop the program?

查看:70
本文介绍了直到停止程序,文件才被写入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行一个测试,发现直到我按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("\n")
  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)保留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天全站免登陆