faqts : Computers : Programming : Languages : Python : Snippets : Stream Manipulation : Files

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

7 of 7 people (100%) answered Yes
Recently 5 of 5 people (100%) answered Yes

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)