okpalan

save_file_incremental

Sep 6th, 2024 (edited)
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.53 KB | None | 0 0
  1. import pickle
  2. import hashlib
  3. import os
  4.  
  5. def get_hash(data):
  6.     """Compute the hash of the given data."""
  7.     hasher = hashlib.sha256()
  8.     hasher.update(data)
  9.     return hasher.hexdigest()
  10.  
  11. def append_incremental_data(filename, new_data, buffer_size=1024):
  12.     """Pickle and append new data to the file incrementally, only if needed."""
  13.    
  14.     # Serialize the new data using pickle
  15.     pickled_data = pickle.dumps(new_data)
  16.    
  17.     # Get the hash of the new pickled data
  18.     new_data_hash = get_hash(pickled_data)
  19.    
  20.     # Check if the file already exists and read its current hash
  21.     if os.path.exists(filename):
  22.         with open(filename, 'rb') as f:
  23.             # Read the file in chunks and calculate its hash
  24.             current_file_hash = hashlib.sha256()
  25.             while chunk := f.read(buffer_size):
  26.                 current_file_hash.update(chunk)
  27.        
  28.         # Compare the current file's hash with the new data hash
  29.         if current_file_hash.hexdigest() == new_data_hash:
  30.             print("No changes detected, no need to update the file.")
  31.             return
  32.         else:
  33.             print("Changes detected, appending new data.")
  34.     else:
  35.         print("File does not exist, creating a new one.")
  36.    
  37.     # Append the new pickled data to the file
  38.     with open(filename, 'ab') as f:
  39.         f.write(pickled_data)
  40.         print("Data appended successfully.")
  41.  
  42. # Example usage
  43. my_dynamic_data = {'key': 'value', 'more_data': [1, 2,
  44.  3]}
  45. append_incremental_data('mydata.pkl', my_dynamic_data)
  46.  
Advertisement
Add Comment
Please, Sign In to add comment