file operations

Eyal Lotem eyal at hyperroll.com
Tue Oct 30 18:46:32 EST 2001


Kerstin wrote:

> begin loop
> - read file
> - replace something in the file (seem to work)
> - write file
> end loop
> 
> This has to be done quite often.

A nice approach to this (if the files are not too large), is to replace the 
loop with something like:

open('filteredfile.output', 'w').writelines(
        map(lambda line: line.rstrip() + '\n',
                open('inputfile', 'r').readlines()))

(opens the input file, reads all lines, replaces every line in the input 
according to the given mapping function, and writes the entire result back 
to the output file).



More information about the Python-list mailing list