[Tutor] overwriting input file

A.T.Hofkamp a.t.hofkamp at tue.nl
Wed Feb 25 13:55:43 CET 2009


Bala subramanian wrote:
> Hello all,
> 
> query 1) How should i overwrite the input file
> I want to open 5 files one by one, do some operation on the lines and write
> the modified lines on the same file (overwritting). Can some please tell me
> how to do it.

You cannot write output to a file if you need the data in the file for input 
first.
You'll have to do it in sequence.

Either first read all input into memory, then open the file for output, or
write the output to a temporary file while reading the input, then rename the 
temporary file.


To prevent problems, be sure to close the input files after reading and before 
you overwrite them.

> query 2) How should I use wild cards to open files in python. Say I have
> files with names *.dat  in a directory, i want the program to open every
> file with extension .dat and do the process.

The glob module should be able to solve that problem for you.


Sincerely,
Albert



More information about the Tutor mailing list