Entry
Process and replace file contents
Jul 5th, 2000 10:00
Nathan Wallace, unknown unknown, Hans Nowak, Snippet 117, Glyn Webster
"""
Packages: files
"""
""" Function to safely process and replace the contents of a file.
Glyn Webster <glyn@ninz.org.nz> 2021-04-27
"""
import os
def file_replacer(filepath, file_processor, readmode="r", writemode="w"):
""" Replace a file with a new one created from it by `file_processor'.
Keeps the old version of the file, with extension ".bak", as a backup.
If `file_processor' fails the output it managed to create is left in a
file with the extension ".$$$".
`file_processor' can be any function that takes two file handle objects
the first open for reading, the second open for writing.
"""
temppath = os.path.splitext(filepath)[0] + '.$$$'
backpath = os.path.splitext(filepath)[0] + '.bak'
ifp = open(filepath, readmode)
ofp = open(temppath, writemode)
try:
file_processor(ifp, ofp)
finally:
ifp.close()
ofp.close()
if os.path.exists(backpath):
os.remove(backpath)
os.rename(filepath, backpath)
os.rename(temppath, filepath)