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, earlier in this chapter, we looked at a few of the most common techniques for 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 the previous run of thelong_complex.py
application. - At time t1, we start running the
long_complex.py
application. It begins overwriting theoutput.csv
file. Until the program finishes, the bytes are unusable. - 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...