Atomic file replacement in Python

北慕城南 提交于 2019-12-01 01:43:21

问题


What's the recommended way to replace a file atomically in 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).

A solution for Linux/UNIX platforms is preferred.

(I know getting 100% atomic operations might depend on your file system, but at least make the chances for the corruption low)


回答1:


Create a new file and os.rename() it over the existing file. This is atomic on most platforms under most conditions.



来源:https://stackoverflow.com/questions/7645338/atomic-file-replacement-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!