Properties file in python (similar to Java Properties)
I was able to get this to work with ConfigParser
, no one showed any examples on how to do this, so here is a simple python reader of a property file and example of the property file. Note that the extension is still .properties
, but I had to add a section header similar to what you see in .ini files... a bit of a bastardization, but it works.
The python file: PythonPropertyReader.py
#!/usr/bin/python import ConfigParserconfig = ConfigParser.RawConfigParser()config.read('ConfigFile.properties')print config.get('DatabaseSection', 'database.dbname');
The property file: ConfigFile.properties
[DatabaseSection]database.dbname=unitTestdatabase.user=rootdatabase.password=
For more functionality, read: https://docs.python.org/2/library/configparser.html
For .ini
files there is the configparser
module that provides a format compatible with .ini
files.
Anyway there's nothing available for parsing complete .properties
files, when I have to do that I simply use jython (I'm talking about scripting).
I know that this is a very old question, but I need it just now and I decided to implement my own solution, a pure python solution, that covers most uses cases (not all):
def load_properties(filepath, sep='=', comment_char='#'): """ Read the file passed as parameter as a properties file. """ props = {} with open(filepath, "rt") as f: for line in f: l = line.strip() if l and not l.startswith(comment_char): key_value = l.split(sep) key = key_value[0].strip() value = sep.join(key_value[1:]).strip().strip('"') props[key] = value return props
You can change the sep
to ':' to parse files with format:
key : value
The code parses correctly lines like:
url = "http://my-host.com"name = Paul = Pablo# This comment line will be ignored
You'll get a dict with:
{"url": "http://my-host.com", "name": "Paul = Pablo" }