Hướng dẫn python atomic file write
I am using Python to write chunks of text to files in a single operation:
If the script is interrupted so a file write does not complete I want to have no file rather than a partially complete file. Can this be done?
martineau 115k25 gold badges160 silver badges283 bronze badges asked Feb 25, 2010 at 12:21
1 Write data to a temporary file and when data has been successfully written, rename the file to the correct destination file e.g
According to doc http://docs.python.org/library/os.html#os.rename
also
Note:
answered Feb 25, 2010 at 12:39
Anurag UniyalAnurag Uniyal 83k39 gold badges169 silver badges216 bronze badges 15
A simple snippet that implements atomic writing using Python
or even reading and writing to and from the same file:
using two simple context managers
answered Apr 7, 2015 at 12:23
Nils WernerNils Werner 32.9k7 gold badges72 silver badges94 bronze badges 8 Since it is very easy to mess up with the details, I recommend using a tiny library for that. The advantage of a library is that it takes care all these nitty-gritty details, and is being reviewed and improved by a community. One such library is
From the README:
Installation via PIP:
answered Jun 28, 2016 at 11:43
vogvog 21.6k11 gold badges57 silver badges73 bronze badges 3 I’m using this code to atomically replace/write a file:
Usage:
It’s based on this recipe. answered Aug 30, 2014 at 19:59
Jakub JirutkaJakub Jirutka 9,6704 gold badges40 silver badges34 bronze badges 2 Just link the file after you're done:
If you want to get fancy:
answered Jan 9 at 17:40
blaisblais 6407 silver badges9 bronze badges Answers on this page are quite old, there are now libraries that do this for you. In particular Their example is just what you want:
It's in PyPI, just install it using answered Aug 17, 2020 at 10:26
EricEric 93310 silver badges21 bronze badges Atomic solution for Windows to loop folder and rename files. Tested, atomic to automate, you can increase probability to minimize risk not to event of having same file name. You random library for letter symbols combinations use random.choice method, for digit str(random.random.range(50,999999999,2). You can vary digits range as you want. |