looping and deleting

Alex Martelli aleax at aleax.it
Tue Apr 22 08:51:12 EDT 2003


Matt Gerrans wrote:

> "Aahz" wrote:
>> Are you trying to modify the file in-place?  If so, look at the
>> fileinput module.  If not:
> 
> I thought the fileinput module was just for gathering all the files on the
> command line into one virtual stream (that is, reading them all without
> respect to filename, as one long series of lines).

Well, then, it's a good thing to learn that fileinput is MUCH more
generally useful than that, isn't it?-)  Look it up...


> I don't know if this is the best or most Pythonic way, but this is what I
> usually do to modify a text file in place (unless I know it will be a
> really big file):
> 
> lines = file( filename ).readlines()
> f = file( filename, 'w' )
> for line in lines:
>    f.write( modifyTheLine(line) )
> f.close()

Sure, if everything fits comfortably in memory this is an excellent
solution, too!


Alex





More information about the Python-list mailing list