4

I have a big binary file. How I can write (prepend) to the begin of the file?

Ex:

file = 'binary_file'
string = 'bytes_string'

I expected get new file with content: bytes_string_binary_file.

Construction open("filename", ab) appends only.

I'm using Python 3.3.1.

4

1 回答 1

11

There is no way to prepend to a file. You must rewrite the file completely:

with open("oldfile", "rb") as old, open("newfile", "wb") as new:
    new.write(string)
    new.write(old.read())

If you want to avoid reading the whole file into memory, simply read it by chunks:

with open("oldfile", "rb") as old, open("newfile", "wb") as new:
    for chunk in iter(lambda: old.read(1024), b""):
        new.write(chunk)

Replace 1024 with a value that works best with your system. (it is the number of bytes read each time).

于 2013-05-05T18:27:31.663 回答