file operations

Eyal Lotem eyal at hyperroll.com
Wed Oct 31 00:46:32 CET 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