Deepika Soren Deepika Soren - 1 year ago 248
Python Question

How to read properties file in python

I have a property file like

I need to read this file and use the variable such as path ,db and data_path in my subsequent scripts.
Can i do this using configParser or simply reading the file and getting the value.
Thanks in Advance.

Answer Source

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 domonstrated 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()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download