"Inserting" a line in a text file?

Bjorn Pettersen BPettersen at NAREX.com
Tue May 7 16:53:39 EDT 2002


> From: Duncan Smith [mailto:buzzard at urubu.freeserve.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.

 fp = file('output', 'w')
 fp.write('new line' + '\n')
 for line in file('input'):
     fp.write(line)
 fp.close()
 os.remove('output')
 os.rename('input', 'output')

is probably as simple as it gets, and I doubt you can do much faster.

still-prefer-open-to-file-but-going-with-the-times'ly y'rs
-- bjorn





More information about the Python-list mailing list