如何进行原子文件替换? [英] How to do atomic file replacement?

查看:55
本文介绍了如何进行原子文件替换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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().这在上的大多数平台上都是原子的.net/man/2/rename"rel =" noreferrer>大多数情况.

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

这篇关于如何进行原子文件替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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