Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys
- class dict_writer:
- def __init__(self, dictionary = {}, file = "dict.txt"):
- self.vars = dictionary
- self.filename = file
- self.generate_file()
- def generate_file(self, dictionary = None):
- """
- Writes the current value of self.vars to the file specified by self.filename.
- If a custom dictionary is supplied by using the keyword argument "dictionary," then
- the specified dictionary will be written instead.
- """
- if dictionary == None: dictionary = self.vars
- with open (self.filename, 'w') as f:
- for keys in dictionary.keys():
- f.write(str(keys) + " = " + str(dictionary.get(keys)) + "\n")
- def read_file(self, sanity = True):
- """
- Reads the file specified by self.filename (defined at initalization) and returns the contents of the file as a dictionary.
- If sanity checking is turned off with the use of the keyword argument "sanity = false" keys in the file will not
- be checked against the dictionary supplied at initialization.
- """
- _dict = {}
- with open (self.filename, 'r') as f:
- for line in enumerate(f):
- value = line[1].strip()
- if value.find("=") < 0:
- sys.stderr.write("Missing '=' in "+self.filename+" on line " + str(line[0] + 1) + ". Cancelling read.")
- return
- else: valIndex = value.find("=")
- key = value[0:valIndex].strip()
- value = value[valIndex + 1:].strip()
- hasQuote = False
- if '"' in value and sanity:
- hasQuote = True
- value = self._parse_quote(value, '"', str(line[0] + 1), sanity = sanity)
- if "'" in value and sanity:
- hasQuote = True
- value = self._parse_quote(value, "'", str(line[0] + 1), sanity = sanity)
- if not hasQuote: value = value.replace(" ", "")
- if self.vars.get(key) == None and not sanity:
- sys.stderr.write('\nInvalid key assignment in '+self.filename+' on line '+str(line[0] + 1)+'.\n'+
- "Ignoring line "+str(line[0] + 1)+'.\n\n')
- else:
- _dict.update({key: value})
- return _dict
- def get_dict(self):
- """Returns self.vars"""
- return self.vars
- def get_value(self, key):
- """
- Searches the dictionary contained by the file at self.filename for the given key and returns it's definition.\n
- If none is found, returns -1
- """
- lineNum = self._get_line(key)
- with open(self.filename, 'r') as f:
- for i in range(lineNum + 1):
- f.readline()
- line = f.readline()
- value = line.strip()
- if value.find("=") < 0:
- sys.stderr.write("Missing '=' in "+self.filename+" on line " + str(lineNum + 1) + ". Cancelling read.")
- return -1
- else: valIndex = value.find("=")
- value = value[valIndex + 1:].strip()
- hasQuote = False
- if '"' in value:
- hasQuote = True
- value = self._parse_quote(value, '"', str(line[0] + 1))
- if "'" in value:
- hasQuote = True
- value = self._parse_quote(value, "'", str(line[0] + 1))
- if not hasQuote: value = value.replace(" ", "")
- return value
- return -1
- def update_value(self, _dict):
- """
- Takes a dictionary as it's argument and updates the dictionary contained by the file at self.filename.
- Does not update self.vars.
- """
- tmp = self.read_file()
- tmp.update(_dict)
- self.generate_file(dictionary=tmp)
- def _parse_quote(self, readStr, char, lineNum):
- """
- Internal class use only
- Ensures that readStr has only one pair of quotes and that they are used correctly
- """
- if len(readStr.strip()[:readStr.find(char)]) > 1:
- sys.stderr.write('\nValue in '+self.filename+' on line '+lineNum+' contains a quote (" '+char+' ") but does not begin with it.\n' +
- 'If whitespace is needed within the value please begin and end value with a quote (" '+char+' ") character.\n'+
- "Ignoring quotes on line "+lineNum+".\n\n")
- return readStr.replace(char, "").strip()
- else:
- tmpStr = readStr[readStr.find(char) + 1:]
- if tmpStr.find(char) < 0:
- sys.stderr.write('\nValue in '+self.filename+' on line '+lineNum+' does not contain a corresponding quote (" '+char+' ").\n'
- "Ignoring quotes on line "+lineNum+".\n\n")
- return readStr.replace(char, "").strip()
- if len(tmpStr[tmpStr.find(char) + 1:]) > 0:
- sys.stderr.write('\nValue in '+self.filename+' on line '+lineNum+' continues after second quote (" '+char+' ").\n'+
- "Ignoring extraneous text on line "+lineNum+".\n\n")
- return tmpStr[:tmpStr.find(char)].strip()
- #this should be unreachable, but is here just in case
- return readStr
- def _get_line(self, key):
- """
- Internal class use only
- Returns the line number in the self.filename of the given key
- """
- lineNum = -1
- with open(self.filename, 'r') as f:
- for i,line in enumerate(f):
- value = line.strip()
- if value.find("=") < 0:
- sys.stderr.write("Missing '=' in "+str(self.filename)+" on line " + str(i) + ". Cancelling read.")
- return -1
- else: valIndex = value.find("=")
- match = value[0:valIndex].strip()
- if key == match:
- lineNum = i - 1
- return lineNum
- return -1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement