Open, edit and save a binary file in Python3

8

You can open a binary file and read its bits in Python3, edit and save a new binary. If so, how?

    
asked by anonymous 03.01.2017 / 16:38

2 answers

7

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

 A0 B0 C0 D0 E0 F0

The following code reads these bytes and changes the byte content at 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
  

Q.: This example "edits" the same file. If you want to create a   second file with the changes, just open it with another name   variable. For example, instead of 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. O    r and + indicate that the file will be opened for reading and for   update, and 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 I use 'rb' ) and the destination ( tgtFile ) I open   only as a recording (and therefore I use 'wb' ). The use of w in opening   of the destination file causes it to always be truncated (if you want to   keep existing content you should open with r+ ).

    
03.01.2017 / 17:01
4

To open a binary-mode file, just use b mode in the open function:

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

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

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

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

    
03.01.2017 / 17:11