Advertisement
furas

Python - pickle/unpickle

Mar 23rd, 2017
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.93 KB | None | 0 0
  1. import pickle
  2.  
  3. # --- functions ---
  4.  
  5. def pickle_data(email_addresses):
  6.     # Open file for binary writing (it will close automatically)
  7.     with open('email_addresses.dat', 'wb') as email_file:
  8.         # Pickle the dictionary and save it to a file.
  9.         pickle.dump(email_addresses, email_file)
  10.  
  11.  
  12. def unpickle_data():
  13.     try:
  14.        
  15.         # Open file for binary reading (it will close automatically)
  16.         with open('email_addresses.dat', 'rb') as email_file:
  17.             # Unpickle the dictionary and assign to variable
  18.             email_addresses = pickle.load(email_file)
  19.            
  20.     except FileNotFoundError:
  21.        
  22.         # Catch exception when file doesn't exist
  23.         email_addresses = {}
  24.  
  25.     return email_addresses
  26.  
  27. # --- main ---
  28.  
  29. # at start unpicle data
  30. data = unpickle_data()
  31.  
  32. print("data:", data)
  33.  
  34. data = {'admin@example.com': 'admin'}
  35.  
  36. # at the end pickle data
  37. pickle_data(data)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement