python中有COMMIT模拟用于写入文件吗?
我有一个打开的文件可供写入,并且一个进程运行了数天——某些内容在相对随机的时刻被写入文件中。 我的理解是——直到我执行 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您应该能够使用 file.flush() 来执行此操作。
You should be able to use
file.flush()
to do this.如果您不想终止当前进程来添加
f.flush()
(听起来它已经运行了好几天了?),应该没问题。 如果您看到正在写入的文件变大,您将不会丢失该数据...来自 Python 文档:
听起来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:
It sounds like Python's buffering system will automatically flush file objects, but it is not guaranteed when that happens.
要确保数据写入磁盘,请使用
file.flush()
,然后使用os.fsync(file.fileno())
。To make sure that you're data is written to disk, use
file.flush()
followed byos.fsync(file.fileno())
.正如已经指出的,使用 .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. :)