what would be a quick way to read a property file in python?

Viewed 27227

I have a file with the format

VarName=Value
.
.

I want to read it into a hash such that H("VarName") will return the value.

What would be a quick way? (read a set of strings, split all of them where the equality sign is, and then put it into a hash?

I am working with python.

10 Answers

OK nobody else in the answers has mentioned it, so I guess I'm going to. If you're writing Python, and have control over your interpreter, maybe you can force the use of the Jython interpreter.

Jython is a Python interpreter implemented entirely in Java. You have all the Python standard libraries at your fingertips, with the additional advantage of all your Java SE libraries available.

I haven't actually executed any of the following (think of it more like psudeo-code without exception handling), but you can mix and match Python and Java libraries, and your code might end up looking something like:

from java.util import Properties
from java.io import File, FileInputStream
import os
javasPropertyObject = Properties()
pathToPropFile = os.path.join('path', 'to', 'property', 'file.properties')
if os.path.isfile(pathToPropFile):
    #this is java.io.File, not Python's file descriptor
    propFile = File(pathToPropFile )
    javasFileInputStreamObject = FileInputStream(propFile)
    javasPropertyObject.load(javasFileInputStreamObject)

    #now we can pull out Java properties as defined by the .property file grammar
    myProp = javasPropertyObject.getProperty('myPropName')

where a file like this will be valid, that wouldn't in the simple split on '=' solutions:

myPropName1:value
myPropName2=value
myPropName3=\
value
#this is a = comment
myPropName4:my \
value
myPropNameWithUnicode=\u0009

The downside, is that you lose your ability to be portable among varying Python interpreters and now you're locked into Jython. You would be locked into a library if you attempt that approach as well. The reason why I like Jython is that your added flexibility with having all of the Java SE libraries available.

Related