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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With