Advertisement
albin900

Python config saver and loader

Jun 18th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.85 KB | None | 0 0
  1. import json
  2.  
  3. class Config:
  4.     def __init__(self, file="config.pycfg"):
  5.         self.file = file
  6.        
  7.     def get(self, key):
  8.         f = open(self.file, "r")
  9.         data = f.read()
  10.         f.close()
  11.         for line in data.splitlines():
  12.             sp = line.split('=')
  13.             if sp[0] == key:
  14.                 return sp[1]
  15.                
  16.         return None
  17.                
  18.     def add(self,key,amount=1):
  19.         d = int(self.get(key))
  20.         if d:
  21.             self.set(key, d+amount)
  22.         else:
  23.             self.set(key, amount)
  24.        
  25.        
  26.     def set(self, key, value):
  27.    
  28.         f = open(self.file, "r+")
  29.         data = f.read()
  30.         f.close()
  31.    
  32.         f = open(self.file, "w+")  
  33.        
  34.         found_line = None
  35.        
  36.         for line in data.splitlines():
  37.             sp = line.split('=')
  38.             if sp[0] == key:
  39.                 found_line = line
  40.                
  41.         new = "%s=%s" % (key, value)
  42.         if found_line:
  43.             data = data.replace(found_line, new)
  44.         else:
  45.             data = "%s\n%s" % (data, new)
  46.        
  47.         f.write(data)
  48.         f.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement