randomly write to a file

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Mon May 7 20:56:59 EDT 2007


On Mon, 07 May 2007 12:51:37 -0700, rohit wrote:

> i can read a specified line by using the module linecache but i am
> struck as to how to implement writing to the n(th) line in a file
> EFFICIENTLY
> which means i don't want to traverse the file sequentially to reach the
> n(th) line

Unless you are lucky enough to be using an OS that supports random-access 
line access to text files natively, if such a thing even exists, you 
can't because you don't know how long each line will be.

If you can guarantee fixed-length lines, then you can use file.seek() to 
jump to the appropriate byte position.

If the lines are random lengths, but you can control access to the files 
so other applications can't write to them, you can keep an index table, 
which you update as needed.

Otherwise, if the files are small enough, say up to 20 or 40MB each, just 
read them entirely into memory.

Otherwise, you're out of luck.


-- 
Steven.



More information about the Python-list mailing list