a nice hot bowl of Enigma Curry

ENIGMA CURRY

Want "perl -p -i -e" like support in python?

The fileinput module allows fairly easy in place editing of files

   1 import fileinput, sys
   2 for line in fileinput.input(["test.txt"],inplace=True):
   3   line=line.replace("car","truck")
   4   #sys.stdout is redirected to the file
   5   sys.stdout.write(line)

What's happening?

Because of inplace=True, the fileinput module first moves test.txt to test.txt.bak (overwriting test.txt.bak if it exists) and then connects sys.stdout to the (new) file test.txt. Writing out every single line with appropriate modifications will create a new file with the net effect being that the file will be the original file with your changes.

Another cool thing is that it works on multiple files and still handles the inplace editing transparently. Just add additional filenames to the list passed to fileinput.input.

PythonInplaceEditing (last edited 2007-11-06 19:25:39 by Ryan)