"Inserting" a line in a text file?

Chris Liechti cliechti at gmx.net
Tue May 7 17:05:32 EDT 2002


"Duncan Smith" <buzzard at urubu.freeserve.co.uk> wrote in
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?  Currently on Win2000, but the solution needs to be cross
> platform.  I can always go with the obvious, but something faster and
> / or simpler would be nice (I might even learn something).  Cheers. 
> TIA. 
 
well you could open the file in bianary read/write and append mode ('ab+'), 
append an empty sequence of the length of your line, then seek to -
BLOCKSIZE*n, copy it seek to -(BLOCKSIZE+len(line))*n, write it. do this 
for 0<n<filesize/BLOCKSIZE.
finally you can seek to the beginning of the file and write your line.

this approach has of course some drawbacks like broken files when you abort 
in the middle and it surely slower than the copy together approach.
the only advantage of it is that it doesn't use the temporary space.

chris

-- 
Chris <cliechti at gmx.net>




More information about the Python-list mailing list