如何安全地写入文件? [英] How to safely write to a file?

查看:119
本文介绍了如何安全地写入文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象你有一个库来处理某种XML文件或配置文件。库将整个文件读入内存,并提供编辑内容的方法。完成操作内容后,您可以调用写入将内容保存回文件。问题是如何以安全的方式执行此操作。



覆盖现有文件(开始写入原始文件)显然不安全。如果写入方法在完成之前失败,最终会写入一半写入文件,并丢失数据。



更好的选择是写入某个临时文件,当写入方法完成时,您复制临时文件到原始文件。



现在,如果复制以某种方式失败,您仍然可以正确保存临时文件中的数据。如果复制成功,您可以删除临时文件。



在POSIX系统上,我想您可以使用重命名系统调用这是一个原子操作。但是,如何在Windows系统上做最好的工作?特别是,如何使用 Python 处理这个最好的方法?



另外,是否有另一种安全写入文件的方案?

解决方案

如果你看到Python的文档,它清楚地提到os.rename()是一个原子操作。所以在你的情况下,将数据写入临时文件,然后将其重命名为原始文件将是相当安全的。



另一种方式可以这样工作:




  • 让原始文件为abc。 xml

  • 创建abc.xml.tmp并向其写入新数据

  • 将abc.xml重命名为abc.xml.bak

  • 将abc.xml.tmp重命名为abc.xml

  • 在新的abc.xml正确放置到位后,删除abc.xml.bak



正如你可以看到,你有abc.xml.bak与你可以用来恢复,如果有任何与tmp文件和复制回来。


Imagine you have a library for working with some sort of XML file or configuration file. The library reads the whole file into memory and provides methods for editing the content. When you are done manipulating the content you can call a write to save the content back to file. The question is how to do this in a safe way.

Overwriting the existing file (starting to write to the original file) is obviously not safe. If the write method fails before it is done you end up with a half written file and you have lost data.

A better option would be to write to a temporary file somewhere, and when the write method has finished, you copy the temporary file to the original file.

Now, if the copy somehow fails, you still have correctly saved data in the temporary file. And if the copy succeeds, you can remove the temporary file.

On POSIX systems I guess you can use the rename system call which is an atomic operation. But how would you do this best on a Windows system? In particular, how do you handle this best using Python?

Also, is there another scheme for safely writing to files?

解决方案

If you see Python's documentation, it clearly mentions that os.rename() is an atomic operation. So in your case, writing data to a temporary file and then renaming it to the original file would be quite safe.

Another way could work like this:

  • let original file be abc.xml
  • create abc.xml.tmp and write new data to it
  • rename abc.xml to abc.xml.bak
  • rename abc.xml.tmp to abc.xml
  • after new abc.xml is properly put in place, remove abc.xml.bak

As you can see that you have the abc.xml.bak with you which you can use to restore if there are any issues related with the tmp file and of copying it back.

这篇关于如何安全地写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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