Open, edit and save a binary file in Python3


It is possible to open a binary file and read its bits in Python3, edit and save a new binary. If possible, how?


Yes, it is possible. Consider an example binary file called teste.bin with the following contents (bytes in hex):

 A0 B0 C0 D0 E0 F0

The following code reads these bytes and changes the content of the byte in position 2 (which initially has the value C0 ) to FF :

with open('teste.bin', 'r+b') as file:
    byte =
    while byte != b'':
        byte =, 0)

Execution result:


Bytes in file after execution:

A0 B0 FF D0 E0 F0

PS: This example "edits" the same file. If you want to create a second file with the changes, just open it with another variable name. For example, instead and using with open , you can do like this:

 srcFile = open('teste.bin', 'rb') tgtFile = open('teste2.bin', 'wb') . . . ... tgtFile.write ... . . . srcFile.close() tgtFile.close()

Note that in the initial example I used 'r+b' to open the file. The r and + indicate that the file will be opened for reading and for updating, and the b indicates that it should be opened as binary instead of text. In this second example, I already open each file in a different way: the source file ( srcFile ) I open only as read (and that's why I use 'rb' ) and the destination file ( tgtFile ) I open only as write (and by this uses 'wb' ). Using w when opening the target file causes it to always be truncated (if you want to keep the existing content you should open it with r+ ).

Scroll to Top