Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read properties file in python

I have a property file called Configuration.properties containing:

path=/usr/bin
db=mysql
data_path=/temp

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.

like image 289
Deepika Soren Avatar asked Jan 14 '15 14:01

Deepika Soren


People also ask

Can Python read properties file?

Reading Properties File in Python The first step is to import the Properties object into our Python program and instantiate it. The next step is to load the properties file into our Properties object. Now, we can read a specific property using get() method or through the index.


1 Answers

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)
like image 101
petedunc88 Avatar answered Sep 24 '22 22:09

petedunc88