0% found this document useful (0 votes)
11 views4 pages

Binary File Operations

Binary file operations file

Uploaded by

gdeep19136
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views4 pages

Binary File Operations

Binary file operations file

Uploaded by

gdeep19136
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

### Binary File Operations with Lists Using `pickle` Module

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.

### File Open Modes

- `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.

### Operations on Binary Files Using Lists


1. Write Data : Serialize a list and write it to the binary file using `pickle.dump()`.
2. Read Data : Deserialize and read the list from the binary file using `pickle.load()`.
3. Append Data : Add more data to the file using `pickle.dump()` in append mode.
4. Update Data : Overwrite the file content by opening it in write mode and writing the updated list.
5. Search Data : While searching in a binary file can be complex, it can be done by reading the entire file
and comparing the data.

### Complete Example with Output

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

# Sample list data


data_to_write = ['Alice', 25, 'New York']

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. Reading data from a binary file (rb mode)


with open('data.bin', 'rb') as file:
loaded_data = pickle.load(file) # Deserialize and read the data
print("Data read from binary file:", loaded_data)

# 3. Appending data to the binary file (ab mode)


additional_data = ['Bob', 30, 'Los Angeles']

with open('data.bin', 'ab') as file:


pickle.dump(additional_data, file) # Serialize and append data to file
print("Additional data appended to binary file:", additional_data)

# 4. Reading all data from the binary file (rb mode)


with open('data.bin', 'rb') as file:
data_list = []
while True:
data_list.append(pickle.load(file)) # Deserialize and add to list
if file.tell() == len(file.read()): # Check if we're at EOF
break
print("All data read from binary file:")
for item in data_list:
print(item)

# 5. Updating data in the binary file (wb mode)


updated_data = ['Alice', 26, 'San Francisco']

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 to confirm the update


with open('data.bin', 'rb') as file:
final_data = pickle.load(file) # Read and confirm the update
print("Updated data read from binary file:", final_data)
```

### Explanation of the Program:

1. Writing Data (`wb`) :


- The list `data_to_write` is serialized and written to the file `data.bin` using the `pickle.dump()` method.

2. Reading Data (`rb`) :


- The data is read back from the binary file using the `pickle.load()` method, which deserializes the list.

3. Appending Data (`ab`) :


- New data (`additional_data`) is appended to the existing file in binary mode using `pickle.dump()`. It
doesn't overwrite the existing data but adds more serialized objects at the end of the file.

4. Reading All Data :


- The program reads all serialized data from the file in a loop and appends each deserialized object to the
`data_list`. The loop is controlled to stop once the file has been fully read.

5. Updating Data (`wb`) :


- The file is opened in `wb` mode, which overwrites the existing file content. A new list (`updated_data`)
is written to the file.

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']
```

### Key Points:

- 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.

- Appending and Updating :


- Appending adds new data to the existing file without overwriting.
- Updating overwrites the existing file with new data.

You might also like