randomly write to a file

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


On Mon, 07 May 2007 14:41:02 -0700, Nick Vatamaniuc wrote:

> Rohit,
> 
> Consider using an SQLite database. It comes with Python 2.5 and higher. 
> SQLite will do a nice job keeping track of the index. You can easily
> find the line you need with a SQL query and your can write to it as
> well. When you have a file and you write to one line of the file, all of
> the rest of the lines will have to be shifted to accommodate, the
> potentially larger new line.


Using an database for tracking line number and byte position -- isn't 
that a bit overkill?

I would have thought something as simple as a list of line lengths would 
do:

offsets = [35, # first line is 35 bytes long
    19, # second line is 19 bytes long...
    45, 12, 108, 67]


To get to the nth line, you have to seek to byte position:

sum(offsets[:n])



-- 
Steven.



More information about the Python-list mailing list