Answer a question

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.

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

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐