Advertisement
tomleo

pickle example

Mar 23rd, 2014
448
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.91 KB | None | 0 0
  1. import pickle
  2.  
  3. class Pickles(object):
  4.  
  5.     def __init__(self):
  6.         self.list = self._read_list_from_file()
  7.  
  8.     def _read_list_from_file(self):
  9.         try:
  10.             with open('list.pkl', 'r+') as f:
  11.                 self.list = pickle.loads(f.read())
  12.         except (IOError, EOFError):
  13.             return []
  14.         return self.list
  15.  
  16.     def display_list(self):
  17.         if self.list:
  18.             print self.list
  19.         else:
  20.             print self._read_list_from_file()
  21.  
  22.     def _update_list(self):
  23.         with open('list.pkl', 'w+') as f:
  24.             f.write(pickle.dumps(self.list))
  25.  
  26.     def append_list(self, *args):
  27.         if not self.list:
  28.             self.list = []
  29.         self.list.extend(args)
  30.         self._update_list()
  31.  
  32.  
  33. if __name__ == '__main__':
  34.     test = Pickles()
  35.     test.append_list(1,2,3,4)
  36.     test.display_list()
  37.     test.append_list(5)
  38.     test.display_list()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement