Writing at the beginning of a file

Bengt Richter bokr at oz.net
Wed Sep 14 20:00:56 EDT 2005


On 14 Sep 2005 07:13:50 -0700, "Thierry Lam" <lamthierry at gmail.com> wrote:

>Let's say I already wrote a file and have the following:
>
>testing
>testing testing
>testing testing testing
>
>Is there an easy way to write something of variable length at the top
>of the file?
>
>For example,
>
>6 testing written
>testing
>testing testing
>testing testing testing
>
>I tried to write some garbage on top right after opening the file and
>then use seek to overwrite the garbage, but since the string to be
>written can be of variable length, I'm not sure how much garbage I have
>to write initially.
>
>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.
>
>Another way of doing it is to buffer the whole file writing into some
>variable, but that means I have to change 2000+ lines of codes and
>change fp.write() to something else.
>
>Any suggestions please?
>
Maybe avoid writing at the beginning?

Consider whether appending suitably tagged info at the end of the
file might work for your actual application. If the file-using program
knows of this structure, it can seek e.g. to the end minus a fixed 4 bytes
and read those, assuming that will an n-digit (or maybe rfind-delimited) ascii
number offset to seek back to the beginning of the variable-length chunk
you appended. Then what you read forward from there can be used as if
prefixed to the whole file (or contain fixup info for other parts of
the file before use). This can be a handy way of incrementally modifying
a file without rewriting the whole. It all depends, but it may be an option ;-)

For real safety though, you don't modify or delete an existing important
file until you know you have a new representation safely completed. I say
"new representation" since that also covers the possiblity of original plus
diff patch file as separate files, which could also be an option.

Regards,
Bengt Richter



More information about the Python-list mailing list