python中有COMMIT模拟用于写入文件吗?

发布于 2024-07-15 06:49:31 字数 241 浏览 4 评论 0原文

我有一个打开的文件可供写入,并且一个进程运行了数天——某些内容在相对随机的时刻被写入文件中。 我的理解是——直到我执行 file.close() 之前——有可能没有任何内容真正保存到磁盘上。 真的吗?

如果主进程尚未完成时系统崩溃怎么办? 有没有一种方法可以每隔...比如 10 分钟进行一次提交(我自己称之为提交——不需要运行计时器)? file.close() 和 open(file,'a') 是唯一的方法,还是有更好的选择?

I have a file open for writing, and a process running for days -- something is written into the file in relatively random moments. My understanding is -- until I do file.close() -- there is a chance nothing is really saved to disk. Is that true?

What if the system crashes when the main process is not finished yet? Is there a way to do kind of commit once every... say -- 10 minutes (and I call this commit myself -- no need to run timer)? Is file.close() and open(file,'a') the only way, or there are better alternatives?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

小…红帽 2024-07-22 06:49:32

您应该能够使用 file.flush() 来执行此操作。

You should be able to use file.flush() to do this.

心安伴我暖 2024-07-22 06:49:32

如果您不想终止当前进程来添加 f.flush() (听起来它已经运行了好几天了?),应该没问题。 如果您看到正在写入的文件变大,您将不会丢失该数据...

来自 Python 文档:

写(str)
将字符串写入文件。 没有返回值。 由于缓冲作用,
该字符串实际上可能不会出现在
文件直到flush()或close()
方法被调用。

听起来Python的缓冲系统会自动刷新文件对象,但不能保证这种情况何时发生。

If you don't want to kill the current process to add f.flush() (it sounds like it's been running for days already?), you should be OK. If you see the file you are writing to getting bigger, you will not lose that data...

From Python docs:

write(str)
Write a string to the file. There is no return value. Due to buffering,
the string may not actually show up in
the file until the flush() or close()
method is called.

It sounds like Python's buffering system will automatically flush file objects, but it is not guaranteed when that happens.

谁人与我共长歌 2024-07-22 06:49:32

要确保数据写入磁盘,请使用 file.flush(),然后使用 os.fsync(file.fileno())

To make sure that you're data is written to disk, use file.flush() followed by os.fsync(file.fileno()).

嘿看小鸭子会跑 2024-07-22 06:49:32

正如已经指出的,使用 .flush() 方法强制从缓冲区中写入,但避免使用大量刷新调用,因为这实际上会减慢您的写入速度(如果应用程序依赖于快速写入)将迫使您的文件系统写入小于缓冲区大小的更改,这可能会让您屈服。 :)

As has already been stated use the .flush() method to force the write out of the buffer, but avoid using a lot of calls to flush as this can actually slow your writing down (if the application relies on fast writes) as you'll be forcing your filesystem to write changes that are smaller than it's buffer size which can bring you to your knees. :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文