如何进行原子文件替换? [英] How to do atomic file replacement?
问题描述
在Python中以原子方式替换文件的推荐方法是什么?
What's the recommended way to replace a file atomically in Python?
即如果Python脚本被中断,出现断电等情况,则文件结束状态不一致(一半写到磁盘)的可能性不大.
i.e. if the Python script is interrupted, there is a power outage etc. files do not have a high probability of ending up in an inconsistent state (half written to the disk).
首选用于Linux/UNIX平台的解决方案.
A solution for Linux/UNIX platforms is preferred.
(我知道获得100%原子操作可能取决于您的文件系统,但至少降低了损坏的可能性.)
(I know getting 100% atomic operations might depend on your file system, but at least make the chances for the corruption low.)
推荐答案
创建一个新文件,并在现有文件上os.rename().这在
Create a new file and os.rename() it over the existing file. This is atomic on most platforms under most conditions.
这篇关于如何进行原子文件替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!