[Tutor] deleting one line in multiple files

Kent Johnson kent37 at tds.net
Fri Sep 14 14:06:29 CEST 2007


bhaaluu wrote:
> On 9/13/07, wormwood_3 <wormwood_3 at yahoo.com> wrote:
> 
>> I think the problem is that the original script you borrowed looks
>> at
the file passed to input, and iterates over the lines in that file,
removing them if they match your pattern. What you actually want to be
doing is iterating over the lines of your list file, and for each line
(which represents a file), you want to open *that* file, do the check
for your pattern, and delete appropriately.
> 
> This is exactly what I'd like to do. =)
> After manually opening about 25 files individually and deleting the line
> that I wanted to delete, and seeing about 175 files left to finish, I thought
> to myself, 'I'm learning Python! Python is supposed to be really good at
> this kind of stuff.'

Good idea! Python is excellent for this kind of stuff.


> The 'fileinput' snippet is one solution, but I'd rather be able to pass it a
> list of filenames to work on, rather than have to manually change the
> filename in the snippet each time. The files are numbered, in order,
> from 0001 to 0175, (filename0001.html to filename0175.html).

Sam has already given you one solution - to pass the list of filenames 
on the command line.

The first argument to fileinput.input() can be a list of filenames, so 
you could do

filenames = open("filelist.list").read().splitlines()
for line in fileinput.input(filenames, inplace=1):
   # etc

> One thought was to be able to change the filename number incrementally,
> assign it to a variable, and run it through a for loop? Isn't it amazing
> how a Newbie approaches a problem? =)

That is arguably a better approach than reading the file, since it 
avoids the effort of creating the file.

for i in range(1, 176):
   filename = 'filename%04d.html' % i
   for line in fileinput.input(filename, inplace=1):
     # etc

Kent


More information about the Tutor mailing list