David_Kassa

xDB

Oct 15th, 2013
912
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.01 KB | None | 0 0
  1. import json, os
  2.  
  3. __version__ = '1.0'
  4. __author__  = 'DirectorX'
  5.  
  6. db_name = 'udb.xdb'
  7. def check_db(name = db_name):
  8.     if not os.path.isfile(name):
  9.         print name + ' database not found\ncreating..'
  10.         udb = open(name,'wb')
  11.         udb.close()
  12.        
  13. def read_db(name = db_name):
  14.     try:
  15.         udb = open(name, 'rb')
  16.     except:
  17.         check_db(name)
  18.         read_db(name)
  19.     try:
  20.         dicT = json.load(udb)
  21.         udb.close()
  22.         return dicT
  23.     except:
  24.         return {}
  25.    
  26. def update_db(newdata, name = db_name):
  27.     data = read_db(name)
  28.     wdb = dict(data.items() + newdata.items())    
  29.     udb = open(name, 'wb')
  30.     json.dump(wdb, udb)
  31.     udb.close()
  32.     check_db(name)
  33.  
  34. def clear_db(name = db_name):
  35.     try:
  36.         os.remove(name)
  37.         check_db(name)
  38.     except:
  39.         print 'Error: ' + name + ' file not found'
  40.  
  41. def del_db(name = db_name):
  42.     try:
  43.         os.remove(name)
  44.     except:
  45.         print 'Error: ' + name + ' file not found'
  46.  
  47.  
  48. if __name__ == '__main__':
  49.     def files():
  50.         print 'Files list:'
  51.         dirs = os.listdir(str(os.getcwd()))
  52.         for file in dirs:
  53.            if '.xdb' in str(file):
  54.                print str(file) + ' (xDB format)'
  55.            else:
  56.                print file
  57.         print
  58.     def cd(dIr):
  59.         os.chdir(dIr)
  60.    
  61.     print __author__ + '  -  Simple database ' + __version__ + ' : for help type: print help_me\n'
  62.     help_me = '''
  63. Commands:
  64. 1) check_db  - using: check_db('DatabaseName.xdb')
  65. 2) read_db   - using: print read_db('DatabaseName.xdb')
  66. 3) update_db - using: update_db({'Key':'Value'} ,'DatabaseName.xdb')
  67. 4) clear_db  - using: clear_db('DatabaseName.xdb')
  68. 5) del_db    - using: del_db('DatabaseName.xdb')
  69.  
  70. 6) files     - using: files()
  71. 7) cd        - using: cd('directory path')
  72.  
  73. 8) exit()    - using: exit() or quit()
  74. '''
  75.     while True:
  76.         try:
  77.             exec(raw_input(str(os.getcwd()) + '> '))
  78.         except Exception as e:
  79.             print 'Error: ' + str(e)
Advertisement
Add Comment
Please, Sign In to add comment