Nearby lessons

93 of 159

Python - Binary Files

📌 What You Will Learn
  • Understand what binary files are and when they are used
  • Know the binary file modes and their meanings
  • Read binary data from a file using rb mode
  • Write binary data to a file using wb mode
  • Copy an image file using binary file operations

Working with Binary Files

Until now, we have worked with text files. Python also supports working with binary files.

Binary files are used to store non-text data such as:

  • Images
  • Audio files
  • Video files
  • PDF documents
  • Executable files

While working with binary files, the file should be opened in binary mode by using rb, wb, ab, etc.

Common Binary File Modes

Mode Description
rb Read binary file.
wb Write binary file.
ab Append binary data.
r+b Read and write binary file.
w+b Write and read binary file.
a+b Append and read binary file.

Example: Copy an Image File

The following program copies the contents of one image file into another image file.

🐍Code Cell
1f1 = open("photo.jpg", "rb")
2 
3data = f1.read()
4 
5f2 = open("newphoto.jpg", "wb")
6 
7f2.write(data)
8 
9print("New Image is available with the name: newphoto.jpg")
10 
11f1.close()
12f2.close()
Output
New Image is available with the name: newphoto.jpg

Explanation

  1. f1 = open("photo.jpg", "rb") opens the source image in read binary mode.
  2. data = f1.read() reads the complete binary contents of the image into data.
  3. f2 = open("newphoto.jpg", "wb") creates a new binary file in write mode.
  4. f2.write(data) writes all binary data into the new image file.
  5. f1.close() and f2.close() close both files after the copy operation.

Why the Copy Is Exact

Text modes can interpret newline characters and encoding. Binary modes do not perform any such conversion.

Because rb and wb work with the raw bytes, the copied image is exactly the same as the original.

Appending Binary Data

To add binary data to the end of an existing binary file, open it in ab mode.

🐍Code Cell
1f = open("audio.bin", "ab")
Output
No output captured.
📝 Key Takeaways
  • Binary files store non-text data such as images, video, audio, and PDFs
  • Binary modes are created by suffixing b to a text mode (rb, wb, ab, etc.)
  • rb reads binary data, wb writes binary data, and ab appends binary data
  • f.read() in binary mode returns the complete binary content as bytes
  • A binary copy writes the exact same bytes, so the copied image is identical

🧠 Test Your Knowledge

6 Questions
Progress: 0 / 6