Created
November 18, 2023 16:36
-
-
Save mridulgain/bae5651392e51d5218e5f9f2d52c586c to your computer and use it in GitHub Desktop.
binary file handeling using python pickel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pickle | |
def write_binary_file(filename, data): | |
with open(filename, 'wb') as file: | |
pickle.dump(data, file) | |
print(f"Data written to {filename}.") | |
def read_binary_file(filename): | |
try: | |
with open(filename, 'rb') as file: | |
data = pickle.load(file) | |
print(f"Data read from {filename}: {data}") | |
except FileNotFoundError: | |
print(f"{filename} not found.") | |
except Exception as e: | |
print(f"Error reading {filename}: {e}") | |
def search_binary_file(filename, key): | |
try: | |
with open(filename, 'rb') as file: | |
data = pickle.load(file) | |
if key in data: | |
print(f"Key '{key}' found in {filename}.") | |
else: | |
print(f"Key '{key}' not found in {filename}.") | |
except FileNotFoundError: | |
print(f"{filename} not found.") | |
except Exception as e: | |
print(f"Error searching in {filename}: {e}") | |
def append_binary_file(filename, new_data): | |
try: | |
with open(filename, 'ab') as file: | |
pickle.dump(new_data, file) | |
print(f"Data appended to {filename}.") | |
except Exception as e: | |
print(f"Error appending to {filename}: {e}") | |
def update_binary_file(filename, key, new_value): | |
try: | |
with open(filename, 'rb') as file: | |
data = pickle.load(file) | |
if key in data: | |
data[key] = new_value | |
with open(filename, 'wb') as updated_file: | |
pickle.dump(data, updated_file) | |
print(f"Key '{key}' updated in {filename}.") | |
else: | |
print(f"Key '{key}' not found in {filename}.") | |
except FileNotFoundError: | |
print(f"{filename} not found.") | |
except Exception as e: | |
print(f"Error updating in {filename}: {e}") | |
# Example usage: | |
filename = "example_binary_file.dat" | |
data_to_write = {"name": "John", "age": 30, "city": "New York"} | |
# Write to a binary file (create if not exists, overwrite if exists) | |
write_binary_file(filename, data_to_write) | |
# Read from the binary file | |
read_binary_file(filename) | |
# Search for a key in the binary file | |
search_binary_file(filename, "age") | |
# Append new data to the binary file | |
new_data_to_append = {"occupation": "Engineer", "salary": 80000} | |
append_binary_file(filename, new_data_to_append) | |
# Update a value in the binary file | |
update_binary_file(filename, "age", 31) | |
# Read the updated file | |
read_binary_file(filename) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment