mad_alien

Babbler

Sep 1st, 2017
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.54 KB | None | 0 0
  1. # Babbler python little test with saving and loading
  2. # has some json saving and loading capabilities
  3. # might help someone
  4.  
  5. from random import choice
  6. import json
  7.  
  8. class Actor:
  9.     def __init__(self,name="Foufoutos", sayings_list=["I am the mighty Foufoutos! Hear me roar!", "Raaaaah!", "GRAAAAAAH!", "Prepare to embrace your creators in the stygian haunts of hell!"]):
  10.         self.name=name
  11.         self.sayings=sayings_list
  12.     def speak(self,criteria=True):
  13.         return (choice(self.sayings))
  14.  
  15. def load_Actor(filename):
  16.     #loads an actor from a json filename and returns an Actor instance initialized with the loaded one
  17.     try:
  18.         with open(filename) as data_file:
  19.             actor_data=json.load(data_file)
  20.     except:
  21.         print ("Error in reading "+filename)
  22.         return None
  23.     if 'name' not in actor_data or 'sayings_list' not in actor_data:
  24.         print ("Wrong data file")
  25.         return None
  26.     else: return Actor(actor_data['name'],actor_data['sayings_list'])
  27.  
  28. def save_Actor(actor,filename):
  29.     try:
  30.         dump_dict={}
  31.         dump_dict['name']=actor.name
  32.         dump_dict['sayings_list']=actor.sayings
  33.         with open(filename, 'w') as outfile:
  34.             json.dump(dump_dict, outfile)
  35.     except:
  36.         print ("Could not save to "+ filename)
  37.         return None
  38.    
  39.    
  40. def main():
  41.     #this is a test function to check and Demo actors functionality
  42.     a=Actor()
  43.     for i in range(10): print (a.speak())
  44.     b=load_Actor('document.json')
  45.     if not b: print ("Load Failed!")
  46.     else:
  47.         print (b.name+" loaded!")
  48.         for i in range(10): print(b.speak())
  49.     save_Actor(a,'testme.json')
  50.        
  51. if __name__ == '__main__':
  52.     main()
Advertisement
Add Comment
Please, Sign In to add comment