Replacing a file while preserving the previous version
We can leverage the power of pathlib
to support a variety of filename manipulations. In the Using pathlib to work with filenames recipe, we looked at a few of the most common techniques of managing directories, filenames, and file suffixes.
One common file processing requirement is to create output files in a fail-safe manner. That is, the application should preserve any previous output file no matter how or where the application fails.
Consider the following scenario:
- At time t0 there's a valid
output.csv
file from yesterday's use of thelong_complex.py
application. - At time t1 we start running the
long_complex.py
application. It begins overwriting theoutput.csv
file. It is expected to finish normally at time t3. - At time t2, the application crashes. The partial
output.csv
file is useless. Worse, the valid file from time t0 is not available either, since it was overwritten.
Clearly, we can make backup copies of files. This introduces an extra...