edit text in a file and save it again

Hendrik van Rooyen mail at microcorp.co.za
Mon Nov 20 06:53:22 CET 2006


"cyberco" <cyberco at gmail.com> wrote:


> I must be overlooking something here... I'm trying to edit a line in a
> text file. I thought this was easy with fileinput, but all examples do
> not write the line back to the file but simply 'print' it. I want to
> open the file, edit the line and save it again. Is fileinput the right
> module for that?

Don't know about the fileinput module - haven't used it -
- but to change a line in a file, you normally have to 
re write the whole thing - think of what has to happen if 
your editing makes a line longer than what it was before
 - how is it going to fit back into the existing,
smaller space?

And if the editing leaves the line shorter, what must be done 
with the existing space that is "left over" and unused?

the way to change a line in a file is normally:

1) read and copy the lines before the line that must be changed to 
a temporary file
2) read the line that needs to be changed, change it in memory,
and write it to the temp file.
3) read and copy the rest of the lines to the temp file.
4) close the files
5) delete the original
6) rename the temp to the original name.

hth - Hendrik





More information about the Python-list mailing list