Parsing .Properties File in Python

Properties file in python (similar to Java Properties)

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).

How to read properties file in python

For a configuration file with no section headers, surrounded by [] - you will find the ConfigParser.NoSectionError exception is thrown. There are workarounds to this by inserting a 'fake' section header - as demonstrated in this answer.

In the event that the file is simple, as mentioned in pcalcao's answer, you can perform some string manipulation to extract the values.

Here is a code snippet which returns a dictionary of key-value pairs for each of the elements in your config file.

separator = "="
keys = {}

# I named your file conf and stored it
# in the same directory as the script

with open('conf') as f:

for line in f:
if separator in line:

# Find the name and value by splitting the string
name, value = line.split(separator, 1)

# Assign key value pair to dict
# strip() removes white space from the ends of strings
keys[name.strip()] = value.strip()

print(keys)

Python property files

The Python equivalent is the configparser to read INI files: https://docs.python.org/3/library/configparser.html

It is similar, but not identical to properties files.

Example INI file, example.ini (copied from the linked documentation):

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no

And a code example (also copied from the documentation):

>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.sections()
[]
>>> config.read('example.ini')
['example.ini']
>>> config.sections()
['bitbucket.org', 'topsecret.server.com']
>>> 'bitbucket.org' in config
True
>>> 'bytebong.com' in config
False
>>> config['bitbucket.org']['User']
'hg'
>>> config['DEFAULT']['Compression']
'yes'

I want to read from Properties file and put that value in a string based on a key from file

Test below code : https://repl.it/repls/EmptyRowdyCategories

from jproperties import Properties

p = Properties()
with open("foobar.properties", "rb") as f:
p.load(f, "utf-8")

print(p["name"].data)
print(p["email"].data)

Crafting a python dictionary based on a .properties file

I copied your function and test your code and made some changes. The below code is working fine.

def setKeyAndValue(storageDict, rowParts):
print rowParts
keyParts = rowParts[0].split('.')
if not keyParts[0] in storageDict.keys():
storageDict[keyParts[0]] = {}
newObj = storageDict[keyParts[0]]
for i in range(len(keyParts)):
if i == len(keyParts)-1:
# Reached the end of the key, save value to dictionary
newObj["val"] = rowParts[1]
else :
# Not yet at the end of the key
if "subKeys" not in newObj:
newObj["subKeys"] = {}
if keyParts[i+1] not in newObj["subKeys"]:
newObj["subKeys"][keyParts[i+1]] = {}
newObj = newObj["subKeys"][keyParts[i+1]]

def main():
input = [
'key1.subkey1.subsubkey1=value1',
'key1.subkey1.subsubkey2=value2',
'key1.subkey2=value3',
'key2=value4'
]
ans = {}
ans1 = {
'subKeys': ans
}

for row in input:
parts = row.split('=', 1)
setKeyAndValue(ans, parts)
print ans1

main()

Output is coming as:

{'subKeys': {'key2': {'val': 'value4'}, 'key1': {'subKeys': {'subkey2': {'val': 'value3'}, 'subkey1': {'subKeys': {'subsubkey1': {'val': 'value1'}, 'subsubkey2': {'val': 'value2'}}}}}}}

Replaced your OutputDict variable with storageDict.keys() and wrote a sample main function. Try running it for yourself and see if it is working for you.

What I think is your OutputDict contains only subKeys key so the condition will always be true and you will replace the previously added dictionary with a blank dictionary.



Related Topics



Leave a reply



Submit