Nearby lessons
93 of 159Python - 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.
Explanation
f1 = open("photo.jpg", "rb")opens the source image in read binary mode.data = f1.read()reads the complete binary contents of the image intodata.f2 = open("newphoto.jpg", "wb")creates a new binary file in write mode.f2.write(data)writes all binary data into the new image file.f1.close()andf2.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.
📝 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 QuestionsProgress: 0 / 6