Binary Files · 2 / 14 Theory

Reading and writing bytes: blocks, seek and in-place changes

Reading the whole file

with open("data.bin", "rb") as f:
    data = f.read()          # the whole content, as bytes

It is the most convenient, and with small files there is no problem. To invert a file, a slice is enough:

with open("data.bin", "rb") as source:
    data = source.read()

with open("data.inv", "wb") as target:
    target.write(data[::-1])     # the last byte first

It is the solution of Inverted file. Always work in binary, even if the file is text: that way line breaks are not altered and no decoding is attempted.

Reading only a part: read(n)

with open("image.bmp", "rb") as f:
    header = f.read(54)      # only the first 54 bytes
    following = f.read(4)    # the next 4 (the file remembers where it is)

read(n) returns at most n bytes. If there are no more, it returns b"" (empty bytes).

Big files: reading in blocks

If the file takes gigabytes, it is not advisable to load it entirely into memory. It is read and written in fixed-size blocks (buffer):

SIZE = 512 * 1024        # 512 Kb

with open("source.bin", "rb") as source, open("copy.bin", "wb") as target:
    while True:
        block = source.read(SIZE)
        if not block:          # b"" is false: the file is over
            break
        target.write(block)

This is the pattern of File copier. Notice that not block is true when the block is empty, and that the last block is usually shorter than the others.

Splitting a file into parts

The same loop serves to distribute the content among new files. A counter inside the name is formatted with leading zeros using :02d:

SIZE = 5 * 1024
number = 1

with open("data.bin", "rb") as source:
    while True:
        block = source.read(SIZE)
        if not block:
            break
        with open(f"data-{number:02d}", "wb") as part:   # data-01, data-02…
            part.write(block)
        number += 1

It is the idea of File splitter. To put the parts back together you would just read them in order and write them one after another in a new file.

Moving around the file: seek() and tell()

with open("data.bin", "rb") as f:
    f.seek(10)          # jump to byte 10 (the first is 0)
    print(f.read(2))    # bytes 10 and 11
    print(f.tell())     # 12: current position
    f.seek(-4, 2)       # 4 bytes before the end (2 = from the end)
    print(f.read())     # the last 4 bytes
CallEffect
f.seek(n)Go to position n from the start
f.seek(n, 1)Move n from the current position
f.seek(-n, 2)Position n bytes before the end
f.tell()Current position

Modifying a file in place: r+b

The "r+b" mode opens an existing file to read and write without deleting it. Writing overwrites the bytes from the current position, without changing the file size:

with open("image.bmp", "r+b") as f:
    mark = f.read(2)
    if mark == b"BM":
        f.seek(0)             # back to the start
        f.write(b"MB")        # overwrites only those two bytes
    else:
        print("Not a valid BMP file")

It is what is asked in Encrypt a BMP image. Notice the seek(0): after reading 2 bytes, the position is at byte 2, and without going back to the start you would write in the wrong place.