user1372972
user1372972

Reputation:

How to prepend data to the binary file?

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.

Upvotes: 4

Views: 2781

Answers (1)

Bakuriu
Bakuriu

Reputation: 101979

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).

Upvotes: 12

Related Questions