#!/usr/bin/python3 # written by andrewtunsw.edu.au as a COMP(2041|9044) lecture example # For each file given as argument replace occurrences of Elizabeth # and shorter forms of the name with Darcy and vice-versa. # Relies on Zaphod not occurring in the text. # use tempfile to create temporary file - robust & secure import re, sys, shutil, tempfile for filename in sys.argv[1:]: with tempfile.NamedTemporaryFile(mode="w", delete=False) as tmp: with open(filename) as f: for line in f: changed_line = re.sub(r"Elizabeth|Lizzy|Eliza", "Zaphod", line) changed_line = changed_line.replace("Darcy", "Elizabeth") changed_line = changed_line.replace("Zaphod", "Darcy") tmp.write(changed_line) shutil.move(tmp.name, filename)