Question:
It is possible to open a binary file and read its bits in Python3, edit and save a new binary. If possible, how?
Answer:
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 = file.read(1)
while byte != b'':
print(byte)
byte = file.read(1)
file.seek(2, 0)
file.write(b'\xFF')
Execution result:
b'\xa0'
b'\xb0'
b'\xc0'
b'\xd0'
b'\xe0'
b'\xf0'
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') . . . srcFile.read ... tgtFile.write ... . . . srcFile.close() tgtFile.close()
Note that in the initial example I used
'r+b'
to open the file. Ther
and+
indicate that the file will be opened for reading and for updating, and theb
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'
). Usingw
when opening the target file causes it to always be truncated (if you want to keep the existing content you should open it withr+
).