Binary File Operations
Binary File Operations
In Python, binary file operations allow you to store and manipulate complex data structures such as lists ,
dictionaries , and objects in binary format. The `pickle` module in Python provides an easy way to serialize
and deserialize data. Below, I will provide a concise guide on performing basic binary file operations using
lists and the `pickle` module.
- `rb`: Read binary mode — Opens a file for reading binary data.
- `wb`: Write binary mode — Opens a file for writing (creates or overwrites the file).
- `ab`: Append binary mode — Opens a file for appending data at the end.
- `rb+`: Read/write binary mode — Opens a file for both reading and writing.
- `wb+`: Write/read binary mode — Opens a file for writing and reading (creates or overwrites the file).
- `ab+`: Append/read binary mode — Opens a file for both appending and reading.
Below is the Python code demonstrating the above binary file operations using lists and the `pickle`
module. The program doesn't use `try` or `except` blocks.
```python
import pickle
1
# 1. Writing data to a binary file (wb mode)
with open('data.bin', 'wb') as file:
pickle.dump(data_to_write, file) # Serialize and write to file
print("Data written to binary file:", data_to_write)
2
with open('data.bin', 'wb') as file:
pickle.dump(updated_data, file) # Overwrite file with updated data
print("Data updated in binary file:", updated_data)
6. Final Reading :
- The final reading of the file confirms that the content has been updated.
3
### Sample Output:
```bash
Data written to binary file: ['Alice', 25, 'New York']
Data read from binary file: ['Alice', 25, 'New York']
Additional data appended to binary file: ['Bob', 30, 'Los Angeles']
All data read from binary file:
['Alice', 25, 'New York']
['Bob', 30, 'Los Angeles']
Data updated in binary file: ['Alice', 26, 'San Francisco']
Updated data read from binary file: ['Alice', 26, 'San Francisco']
```
- File Modes :
- `wb`: Used to create a new file or overwrite an existing one.
- `rb`: Used to read binary data.
- `ab`: Used to append data to the end of a binary file.
- `wb+` , `rb+` , and `ab+` are read/write modes but are not used here for simplicity.
- Operations :
- pickle.dump() serializes data and writes it to a file in binary form.
- pickle.load() deserializes the binary data and returns the Python object.