Writing at the beginning of a file
tjreedy at udel.edu
Thu Sep 15 02:33:14 CEST 2005
"Thierry Lam" <lamthierry at gmail.com> wrote in message
news:1126707230.693569.187200 at g49g2000cwa.googlegroups.com...
> Is there an easy way to write something of variable length at the top
> of the file?
> The other way to do what I want is to write the whole thing to a new
> file, but I want to skip that method if there's an alternative way.
Grant has already given you the two no's to the questions you asked.
> Any suggestions please?
A slightly different question "How do I write a variable length file
summary after writing the data so that the summary is easy to read without
reading the entire file, and so I can add data later?" has a yes answer:
1. reserve a fixed amount of space at the top for a 'pointer' to the
2. write the data
3. write the summary
4. rewind (seek to beginning) and write the 'pointer'.
The pointer can be either the offset from the beginning or the offset from
the end (= length of summary) in either binary or text format.
To read, read the pointer, seek to appropriate place, and read summary.
To add data:
1. read the summary
2. write more data, starting where the old summary started
3. write revised summary and pointer.
Terry J. Reedy
More information about the Python-list