Modifying a row in a textfile

Dave Angel davea at
Sat Sep 12 16:52:24 CEST 2009

Jorgen Grahn wrote:
> On Tue, 08 Sep 2009 14:21:59 +0200, Diez B. Roggisch <deets at> wrote:
>> Olli Virta wrote:
>>> Hi!
>>> I got a textfile made out of database records. Is there an easy way to
>>> modify rows in that file in case you have to take away some items here
>>> and there from each rows.
>> for line in inf.readlines():
>>     if matches_criteria(line):
>>        line = modify_line(line)
>>     outf.write(line)
> In other words, no. You need to put the results in another file.
> /Jorgen
If it is important that this ends up in the same file, you can simplify 
the code by using fileinput.input() with the "inplace" paramater.  It 
renames the input file, redirects stdout to a new file with the original 
name, and deletes the renamed file, all at appropriate times.  There are 
a few caveats, so be careful.  The main caveat is to make sure you close 
the file.


More information about the Python-list mailing list