[Tutor] Changing lines in a set of files
Karen Windus
kwindus@hotmail.com
Thu, 08 Mar 2001 20:36:16
Hi -
I've been wrestling with this problem for about a week now (I'm a newbie).
I want to open a series of files from a directory, matchand replace a
substring in the files and then (here's the tricky part for me) save and
close the files.
This script works, until I introduced the input and output file objects.
I'm not so sure how the input and output files work. Here's what I have so
far:
#! /usr/bin/env python
import string, sys, fileinput
# take the first argument out of sys.argv and assign it to searchterm
searchterm, sys.argv[1:] = sys.argv[1], sys.argv[2:]
inputfiles, outputfiles = fileinput.input()
for inputfilename in inputfilenames:
for line in fileinput.input():
num_matches = string.count(line, searchterm)
new_string = string.replace(line,searchterm,"Feedback")
if num_matches:
inputfile = open(fileinput.filename(), 'r')
new_string = string.replace(line,searchterm,"Feedback")
print new_string
# a nonzero count means there was a match
print "found '%s' %d times in %s on line %d." % (searchterm,
num_matches,
fileinput.filename(), fileinput.filelineno())
outputfiles=open(fileinput.filename(),'w')
write_results(outputfiles)
fileinput.nextfile()
_________________________________________________________________
Get your FREE download of MSN Explorer at http://explorer.msn.com