Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to open a binary file in read and write mode with Python?
A binary file is a file that consists of a series of 1's and 0's, typically used to represent data such as images, audio, video, and executables. Python provides the built-in open() function to work with binary files in read and write mode.
The open() Function
The Python open() function is a built-in function used to open files. It accepts a file path as a parameter and returns a file object. You can specify the mode parameter to control how the file is opened.
Syntax
open(file, mode)
Binary File Modes
To open a binary file in read and write mode, Python provides two main modes ?
-
rb+ − Opens an existing file for both reading and writing in binary format. The file must exist or it raises
FileNotFoundError. File contents are not cleared. - wb+ − Opens a file for both reading and writing in binary format. Creates a new file if it doesn't exist. Clears existing content to zero length.
Note: Use 'rb+' to read and modify existing binary files. Use 'wb+' to start with a fresh file.
Example: Using wb+ Mode
The 'wb+' mode creates a new file or clears existing content, then allows both reading and writing ?
# Using wb+ mode to write and read
with open('example.bin', 'wb+') as file:
# Write binary data
file.write(b'Welcome to Tutorialspoint!!')
# Move to beginning to read
file.seek(0)
content = file.read()
print(content)
b'Welcome to Tutorialspoint!!'
Example: Using rb+ Mode
The 'rb+' mode opens an existing binary file for reading and writing without clearing content ?
# First create a file with some content
with open('data.bin', 'wb') as file:
file.write(b'Hello World')
# Now use rb+ to read and modify
with open('data.bin', 'rb+') as file:
# Read existing content
print("Original:", file.read())
# Write at the beginning
file.seek(0)
file.write(b'Hi')
# Read the modified content
file.seek(0)
print("Modified:", file.read())
Original: b'Hello World' Modified: b'Hi World'
Key Differences
| Mode | File Must Exist | Clears Content | Best For |
|---|---|---|---|
rb+ |
Yes | No | Modifying existing files |
wb+ |
No | Yes | Creating new files |
Note: The 'b' prefix in the output (like b'Hello') indicates a byte string, which represents binary data rather than Unicode text.
Conclusion
Use 'wb+' mode when you need to create a fresh binary file with read/write access. Use 'rb+' mode when you want to modify an existing binary file without losing its original content.
