Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # libraryfolders.vdf
- # libraryfolder.vdf
- # appmanifest_%d.acf
- # appworkshop_%d.acf
- class VDF_ParseError(Exception):
- def __init__(self, msg, line, col):
- self.msg = msg
- self.line = line
- self.col = col
- def __str__(self):
- return self.msg + " (line %d column %d)" % (self.line + 1, self.col + 1) # +1 for 0-based to 1-based
- def read(path):
- """Returns dictionary of {key: value or sub}, case sensitive."""
- with open(path, "r") as f:
- escape = False
- in_quote = False
- words = []
- root = {}
- section = root
- section_history = []
- for line, row_content in enumerate(f):
- for col, c in enumerate(row_content):
- if in_quote:
- if c in "\r\n":
- raise VDF_ParseError("unterminated string %r" % word, line, col)
- elif escape:
- escape = False
- # c is an escaped character (not handled for now)
- words[-1] += "\\" + c
- elif c == in_quote:
- in_quote = False
- if len(words) == 2:
- key, value = tuple(words)
- section[key] = value
- words = []
- elif len(words) > 2:
- raise VDF_ParseError("expected 2 items for key and value but got %d items" % len(words), line, col)
- elif c == "\\":
- escape = True
- else:
- words[-1] += c
- elif c in "'\"":
- in_quote = c
- words += [""]
- elif c == "{":
- if len(words) != 1:
- raise VDF_ParseError("expected exactly 1 item before opening brace but got %d items" % len(words), line, col)
- new_section = {}
- section_history.append(section)
- section[words[0]] = new_section
- section = new_section
- words = []
- elif c == "}":
- if len(section_history) <= 0:
- raise VDF_ParseError("closing brace not expected", line, col)
- section = section_history.pop()
- elif not c.isspace():
- raise VDF_ParseError("unexpected symbol %r" % c, line, col)
- if len(section_history) > 0:
- raise VDF_ParseError("%d braces left unclosed" % len(section_at)-1, line, col)
- return root
- def write(f, vdf, lvl=0):
- for key, value in vdf.items():
- if type(value) is dict:
- f.write("\t"*lvl + "\"%s\"\n" % str(key))
- f.write("\t"*lvl + "{\n")
- write(f, value, lvl+1)
- f.write("\t"*lvl + "}\n")
- elif type(value) is str:
- f.write("\t"*lvl + "\"%s\"\t\t\"%s\"\n" % (str(key), str(value)))
- else:
- raise TypeError("expected dict or str not %r" % type(value))
- if __name__ == "__main__":
- vdf = read(r"C:\Program Files (x86)\Steam\steamapps\libraryfolders.vdf")
- # How to use (KeyError is raised if you enter invalid key)
- print(vdf["libraryfolders"]["0"])
- # Display all
- #~ with open(1, "w") as f:
- #~ write(f, vdf)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement