[Tutor] Changing lines in a set of files

Jörg Wölke lumbricus@gmx.net
Fri, 9 Mar 2001 05:27:31 +0100 (MET)


> 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

I hope I don't miss the point here but I don't think this one does
what you want:
> searchterm, sys.argv[1:] = sys.argv[1], sys.argv[2:]
                             ^^^^^^^^^^^^^^^^^^^^^^^^^
                             this packs a tuple of ( <first arg>,           
                      <second arg>
                          and...
^^^^^^^^^^^^^^^^^^^^^^^^^^
unpacks it to searchterm and <first arg>

==

searchterm=sys.argv[2:]
sys.argv[1:]=sys.argv[1]

you want:
searchterm=sys.argv[1]       # cause sys.argv[0] is the commandname         
                      # itself


Or am I completely missing the point??

didn't look at fileinput module yet:
> 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
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Sent through GMX FreeMail - http://www.gmx.net