Inserting empty space into an existing file/pointer

Greg Ewing greg.ewing at compaq.com
Tue Jul 6 17:58:10 EDT 1999


NO_SPAMnpirzkal at hq.eso.org wrote:
> 
> I have the need to insert some empty space inside an already existing binary
> file. Is there a convenient, quick way of doin gthis with Python?

The simplest way is to read everything after the
insertion point into memory, and then write it back
further along in the file, e.g.:

f = open("myfile", "rb+")
f.seek(2047*1024)
data = f.read()
f.seek(2147*1024)
f.write(data)
f.close()

If there's too much data to fit in memory, you
could start at the end of the file and work
backwards, reading and writing suitable
sized chunks, but it would be messy to write.

Greg




More information about the Python-list mailing list