Dan The Man
Dan The Man

Reputation: 1895

Python - writing to file to a given offset

I have a binary file name binary_dump that looks like this

xxd binary_dump
0000000: 0000 4865 6c6c 6f20 776f 726c 6421 0000    ..Hello world!..
0000010: 726c 6421 726c 6421                        rld!rld!

my objective is with a given offset to write lets say /00/00/00/00 instead of the string is currently in the given offset

i am using python and this is my code

    file = open('binary_dump', "w")
    file.seek(2) 
    data= "\00\00\00\00"
    file.write(data) 
    file.close()

what i am getting is this:

xxd binary_dump
0000000: 0000 0000 0000                           ......

any ideas?

Upvotes: 4

Views: 5440

Answers (2)

Selcuk
Selcuk

Reputation: 59228

You are truncating the file with w mode and not opening it in binary mode (if you are using Windows). Change the mode from w to r+b:

file = open('binary_dump', "r+b")

See Python documentation on Input and Output for details:

'w' for only writing (an existing file with the same name will be erased) [...]. 'r+' opens the file for both reading and writing.

Upvotes: 1

viraptor
viraptor

Reputation: 34155

Read about the open modes in the docs. The mode you want is most likely "r+b", rather than "w" - it won't truncate the file.

Upvotes: 1

Related Questions