14
Lesson 30 of 44

Binary Files

Binary files store data in its raw form and are essential for handling information in its original format, such as MP3 files or BMP images. In this lesson, you will learn how to work with binary files in Python and perform advanced operations.

  • 4 theory articles
  • 10 practice exercises
Start lesson

Fundamentals concepts 4

What is a binary file and the bytes type

All files store bytes (numbers from 0 to 255). A text file is the case in which those bytes represent letters according to an…

Theory
Read more

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

with open("data.bin", "rb") as f: data = f.read() # the whole content, as bytes It is the most convenient, and with small files…

Theory
Read more

File formats: headers, offsets and struct

A binary file is not a pile of random bytes: it follows a format that says what each byte means according to its position…

Theory
Read more

Showing bytes in hexadecimal and common mistakes

To inspect a binary file a hexadecimal viewer is used: it shows the bytes in hexadecimal and, next to them, those that correspond…

Theory
Read more

Practice exercises 10

Read ID3 v1 tags from MP3 file

Create a Python program that reads ID3 v1 specification tags from an MP3 music file. You should also check if the ID tag…

Exercise Medium
Solve it

Read dimensions of BMP image

Create a program in Python that reads the dimensions of an image in Windows bitmap (BMP) format. First check that it is a valid…

Exercise Medium
Solve it

Encrypt a BMP image

Create a program in Python that encrypts an image in Windows bitmap (BMP) format. First check that it is a valid .bmp image by…

Exercise Medium
Solve it

Inverted file

Create a program in Python that inverts all the bytes of a binary file. Open the files in binary mode ( rb and wb ). You must…

Exercise Medium
Solve it

File copier

Create a Python program that makes copies of text and binary files. Open the files in binary mode and copy them in blocks…

Exercise Medium
Solve it

File splitter

Create a Python program that divides text or binary files into parts of 5 Kb each. Open the files in binary mode to read the…

Exercise Medium
Solve it

Hexadecimal viewer

Create a hexadecimal viewer in Python that shows the contents of a binary file on screen as follows:

Exercise Medium
Solve it

Binary records with struct

Binary record files store each field in a fixed size. struct converts Python values to bytes and back according to a format .

Exercise Hard
Solve it

Checksum of a file

To check that a file has not been corrupted, a checksum is computed by reading it in blocks, without loading it whole into memory.

Exercise Medium
Solve it

Recognize the type of a file

The extension of a file name can lie; the content cannot. Many formats start with fixed bytes (a magic number ) that identify…

Exercise Medium
Solve it