Open, edit and save a binary file in Python3

Asked

Viewed 6,367 times

11

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

2 answers

10


Yes, it is possible. Consider a binary file called teste.bin example with the following content (hexadecimal bytes):

 A0 B0 C0 D0 E0 F0

The following code reads these bytes and changes the byte content at the position 2 (that initially has the value C0) for 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')

Outturn:

b'\xa0'
b'\xb0'
b'\xc0'
b'\xd0'
b'\xe0'
b'\xf0'

Bytes in the file after execution:

A0 B0 FF D0 E0 F0

P.S.: This example "edits" the same file. If you want to create one second file with the changes, just open it with another name of variable. For example, use instead with open, you can do thus:

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. The r and the + indicate that the file will be opened for reading and for update, and the b indicates that it should be opened as binary to the instead of text. In this second example, I already open each file in a distinct mode: the source file (srcFile) I open only as reading (and therefore use 'rb') and the destination (tgtFile) I open it only as recording (and therefore use 'wb'). The use of w at the opening of the target file makes it always be truncated (if you want keep the existing content you must open with the r+).

4

To open a file in binary mode just use the mode b in office open:

open("arquivo", "r+b") # Abre arquivo em modo binário para edição

From there, all normal file reading, writing and browsing functions are valid:

with open("arquivo", "r+b") as arquivo:
    byte = arquivo.read(1)
    # altera byte
    arquivo.write(byte)

Remembering that as the file was opened in binary mode, all functions will accept and return byte objects.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.