Created
June 27, 2012 17:26
-
-
Save codemaniac/3005555 to your computer and use it in GitHub Desktop.
property file/value file parser in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# -*- coding: utf-8 -*- | |
import sys | |
class _ValueFileParserError(Exception): | |
pass | |
class ValueFileParser: | |
def __init__(self, path): | |
self.convertor = lambda v,t : map(t,v) if type(v) is list else t(v) | |
try: | |
f = open(path) | |
self.props = {} | |
for p in f.readlines(): | |
# use non-comment lines. comment lines begin with a '#' | |
if p[0] != '#': | |
try: | |
# isolate key-value pairs | |
key,value = p.split('=', 1) | |
# strip away any leading/training spaces | |
key,value = key.strip(),value.strip() | |
# handle inline comments | |
end = value.find('#') | |
value = value[:end] if end != -1 else value | |
# handle list of values for a key | |
value = value.split(';') if len(value.split(';')) > 1 else value | |
# associate value with key | |
self.props[key] = value | |
except ValueError: | |
# non key-value pair line obtained | |
continue | |
except IOError: | |
raise | |
except: | |
raise _ValueFileParserError("Unable to parse property file") | |
def get_value(self, key, type=str): | |
return self.props[key] if type is str else self.convertor(self.props[key], type) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment