Advertisement
Guest User

dict_writer.py

a guest
Oct 21st, 2019
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.96 KB | None | 0 0
  1. import sys
  2.  
  3. class dict_writer:
  4.  
  5.     def __init__(self, dictionary = {}, file = "dict.txt"):
  6.         self.vars = dictionary
  7.         self.filename = file
  8.         self.generate_file()
  9.  
  10.     def generate_file(self, dictionary = None):
  11.         """
  12.        Writes the current value of self.vars to the file specified by self.filename.
  13.        If a custom dictionary is supplied by using the keyword argument "dictionary," then
  14.        the specified dictionary will be written instead.
  15.        """
  16.         if dictionary == None: dictionary = self.vars
  17.         with open (self.filename, 'w') as f:
  18.             for keys in dictionary.keys():
  19.                 f.write(str(keys) + " = " + str(dictionary.get(keys)) + "\n")
  20.  
  21.     def read_file(self, sanity = True):
  22.         """
  23.        Reads the file specified by self.filename (defined at initalization) and returns the contents of the file as a dictionary.
  24.        If sanity checking is turned off with the use of the keyword argument "sanity = false" keys in the file will not
  25.        be checked against the dictionary supplied at initialization.
  26.        """
  27.         _dict = {}
  28.         with open (self.filename, 'r') as f:
  29.             for line in enumerate(f):
  30.                 value = line[1].strip()
  31.                 if value.find("=") < 0:
  32.                     sys.stderr.write("Missing '=' in "+self.filename+" on line " + str(line[0] + 1) + ". Cancelling read.")
  33.                     return
  34.                 else: valIndex = value.find("=")
  35.                 key = value[0:valIndex].strip()
  36.                 value = value[valIndex + 1:].strip()
  37.                 hasQuote = False
  38.                 if '"' in value and sanity:
  39.                     hasQuote = True
  40.                     value = self._parse_quote(value, '"', str(line[0] + 1), sanity = sanity)
  41.                 if "'" in value and sanity:
  42.                     hasQuote = True
  43.                     value = self._parse_quote(value, "'", str(line[0] + 1), sanity = sanity)
  44.                 if not hasQuote: value = value.replace(" ", "")
  45.                 if self.vars.get(key) == None and not sanity:
  46.                     sys.stderr.write('\nInvalid key assignment in '+self.filename+' on line '+str(line[0] + 1)+'.\n'+
  47.                     "Ignoring line "+str(line[0] + 1)+'.\n\n')
  48.                 else:
  49.                     _dict.update({key: value})
  50.         return _dict
  51.    
  52.     def get_dict(self):
  53.         """Returns self.vars"""
  54.         return self.vars
  55.  
  56.     def get_value(self, key):
  57.         """
  58.        Searches the dictionary contained by the file at self.filename for the given key and returns it's definition.\n
  59.        If none is found, returns -1
  60.        """
  61.         lineNum = self._get_line(key)
  62.         with open(self.filename, 'r') as f:
  63.             for i in range(lineNum + 1):
  64.                 f.readline()
  65.             line = f.readline()
  66.             value = line.strip()
  67.             if value.find("=") < 0:
  68.                 sys.stderr.write("Missing '=' in "+self.filename+" on line " + str(lineNum + 1) + ". Cancelling read.")
  69.                 return -1
  70.             else: valIndex = value.find("=")
  71.             value = value[valIndex + 1:].strip()
  72.             hasQuote = False
  73.             if '"' in value:
  74.                 hasQuote = True
  75.                 value = self._parse_quote(value, '"', str(line[0] + 1))
  76.             if "'" in value:
  77.                 hasQuote = True
  78.                 value = self._parse_quote(value, "'", str(line[0] + 1))
  79.             if not hasQuote: value = value.replace(" ", "")
  80.             return value
  81.         return -1
  82.    
  83.     def update_value(self, _dict):
  84.         """
  85.        Takes a dictionary as it's argument and updates the dictionary contained by the file at self.filename.
  86.        Does not update self.vars.
  87.        """
  88.         tmp = self.read_file()
  89.         tmp.update(_dict)
  90.         self.generate_file(dictionary=tmp)
  91.  
  92.     def _parse_quote(self, readStr, char, lineNum):
  93.         """
  94.        Internal class use only
  95.        Ensures that readStr has only one pair of quotes and that they are used correctly
  96.        """
  97.         if len(readStr.strip()[:readStr.find(char)]) > 1:
  98.             sys.stderr.write('\nValue in '+self.filename+' on line '+lineNum+' contains a quote (" '+char+' ") but does not begin with it.\n' +
  99.             'If whitespace is needed within the value please begin and end value with a quote (" '+char+' ") character.\n'+
  100.             "Ignoring quotes on line "+lineNum+".\n\n")
  101.             return readStr.replace(char, "").strip()
  102.         else:
  103.             tmpStr = readStr[readStr.find(char) + 1:]
  104.             if tmpStr.find(char) < 0:
  105.                 sys.stderr.write('\nValue in '+self.filename+' on line '+lineNum+' does not contain a corresponding quote (" '+char+' ").\n'
  106.                 "Ignoring quotes on line "+lineNum+".\n\n")
  107.                 return readStr.replace(char, "").strip()
  108.             if len(tmpStr[tmpStr.find(char) + 1:]) > 0:
  109.                 sys.stderr.write('\nValue in '+self.filename+' on line '+lineNum+' continues after second quote (" '+char+' ").\n'+
  110.                 "Ignoring extraneous text on line "+lineNum+".\n\n")
  111.                 return tmpStr[:tmpStr.find(char)].strip()
  112.         #this should be unreachable, but is here just in case
  113.         return readStr
  114.    
  115.     def _get_line(self, key):
  116.         """
  117.        Internal class use only
  118.        Returns the line number in the self.filename of the given key
  119.        """
  120.         lineNum = -1
  121.         with open(self.filename, 'r') as f:
  122.             for i,line in enumerate(f):
  123.                 value = line.strip()
  124.                 if value.find("=") < 0:
  125.                     sys.stderr.write("Missing '=' in "+str(self.filename)+" on line " + str(i) + ". Cancelling read.")
  126.                     return -1
  127.                 else: valIndex = value.find("=")
  128.                 match = value[0:valIndex].strip()
  129.                 if key == match:
  130.                     lineNum = i - 1
  131.                     return lineNum
  132.             return -1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement