Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import copy
- import shutil
- class Preferences:
- """Simple Class for reading and writing preferences to a file"""
- _pref = {}
- _sections = []
- def __init__(self, fileName):
- self._file = fileName
- self._loadPreferences_()
- def __repr__(self):
- """Defines what happens when the object is printed out"""
- out = ""
- for sk,sv in self._pref.items():
- out += "[%s]\n" % (sk)
- for ik,iv in sv.items():
- out += "%s = %s\n" % (ik,iv)
- return out
- def _loadPreferences_(self):
- """
- Reads in the preferences's from a file
- Ignores lines that start with # or ; (comments)
- Comments must be on their own line
- """
- pref = {}
- pref["Main"] = {}
- sections = ["Main"]
- curSection = "Main"
- fh = open(self._file,"r+")
- for line in fh:
- if line[:1] == '#' or line == "\n" or line[:1] == ';':
- continue
- if line[:1] == '[':
- curSection = line.strip()[1:-1]
- sections.append(line.strip()[1:-1])
- pref[curSection] = {}
- continue
- p = line.split('=')
- pref[curSection][p[0].replace('"', '').strip()] = p[1].replace('"', '').strip()
- fh.close()
- self._pref = pref
- self._sections = sections
- def getPreferences(self):
- """
- Returns a Deepcopy of a Dictionary
- Contains Dictionaries for each section in preference file
- """
- return copy.deepcopy(self._pref)
- def savePreferences(self, pref, backup = False):
- """
- Takes the supplied dictionary and writes it to file
- Curently overrides orginal file
- Optionaly makes backup of original file
- """
- lines = ""
- sections = []
- for k in pref.keys():
- sections.append(k)
- sections.insert(0, sections.pop(sections.index('Main')))
- for section in sections:
- if not section == 'Main':
- lines += "\n[%s]\n" % (section)
- for k,v in pref[section].items():
- lines += "%s = %s\n" % (k,v)
- if backup:
- #Do Backup
- shutil.copy2(self._file,"%s.bak" % (self._file))
- fh = open(self._file, "w")
- fh.write(lines)
- fh.close()
- def listSections(self):
- """Lists the sections in a preference file"""
- return self._sections
- def getDifferences(self, oldPref, newPref):
- """
- Compares two dictionaries and returns a tuple
- The tuple contains 3 dictionaries(changed, inserted, deleted)
- """
- changedPref = {}
- insertPref = {}
- delPref = {}
- for k,v in newPref.iteritems():
- if (k not in oldPref):
- insertPref[k] = v
- continue
- if (not oldPref[k] == v):
- changedPref[k] = v
- for k,v in oldPref.iteritems():
- if (k not in newPref):
- delPref[k] = v
- return updatePref, insertPref, delPref
- if __name__ == "__main__":
- tp = Preferences("test2.ini")
- pref = tp.getPreferences()
- pref["New"] = {}
- pref["New"]["Bad"] = "Good"
- tp.savePreferences(pref)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement