"Inserting" a line in a text file?

Raymond Hettinger python at rcn.com
Tue May 7 16:44:30 EDT 2002


"Duncan Smith" <buzzard at urubu.freeserve.co.uk> wrote in message
news:ab9duj$dre$1 at newsg4.svr.pol.co.uk...
> I need to (in effect) insert a single line at the beginning of an existing
> text file (a dumped MySQL database, so potentially large).  Is there
> anything cuter than  eg. creating a temporary file containing the single
> line, reading the lines from the data file, appending them to the
temporary
> file, deleting the data file, renaming the temporary file?

Something akin to this HAS to be done, because all of the subsequent lines
need to be moved down in file position.

A fast way is to let the operating system do the work (use the os module):

rename tgtfile tempfile              # very fast
cat 'new single line' >  tgtfile    # very fast
cat tempfile >> tgtfile                # the slow step
del tempfile                               # very fast


Raymond Hettinger





More information about the Python-list mailing list