insert line in middle of file

Alex Martelli aleaxit at yahoo.com
Mon Apr 2 15:13:09 EDT 2001


"Kragen Sitaker" <kragen at dnaco.net> wrote in message
news:N13y6.19325$BC6.5304590 at e3500-chi1.usenetserver.com...
> In article <9aacgo$7da$1 at solaria.cc.gatech.edu>,
> Holland King  <insanc at cc.gatech.edu> wrote:
> >i have a file that must have some stuff at the beginning and the end and
i
> >need to add a line to the middle. is there any easy way to do this
without
> >losing data? thank you.
>
> Copy the beginning to a new file, write the added line to the new file,
> and copy the end to the new file.  Then rename the new file to have the
> same name as the old one.

Excellent summary of the needed underlying operations.  I'd just
like to add that the standard Python fileinput module may be a good
way to wrap these operations up in certain cases, at a somewhat
higher logical level, thanks to the 'inplace' and 'backup' arguments.

E.g., say you want to rewrite ``in-place'' a file "a.txt" by adding a
line "Foopie!" each time it now has a like starting with a lowercase
'x' (peculiar task, but we have all seen worse:-).  fileinput makes
this pretty easy:

import fileinput
for line in fileinput.input('a.txt',inplace=1):
    print line[:-1]
    if line.startswith('x'): print "Foopie!"

Standard output is redirected to (a fresh version of) the file(s)
being read, so you only need to 'print' right back any line you
want to "preserve" (here, all of them) -- just remember that
print adds a newline, so you need to remove the trailing ones
already present in the lines you have read -- and add or
substitute, again with 'print', whatever new or changed lines
you wish (you can also 'delete', so to speak, any input lines,
by just not printing them out again...).


In other cases, of course, one may prefer to have all the text
in memory at once (as a list of lines), edit it appropriately
with list means (assignment to list-slices being very good for
such editing:-), and write it out again with .writelines...


Alex






More information about the Python-list mailing list