Reputation: 51
[section 1]
key1:value1
key2:value2
[section 2]
key1:value1
key2:value2
I have tried to parse this config file into dictionary using python but i was unable to do
This is my code:
import configparser
config = configparser.ConfigParser
filename = '/home/Documents/dictionary parsing/config.cfg'
def read_config_file(filename):
with open(file=filename, mode='r') as fs:
return{k.strip(): v.strip() for i in [l for l in fs.readlines() if l.strip() != ''] for k, v in [i.split('=')]}
print('dictionary: ',read_config_file(filename))
Upvotes: 3
Views: 3981
Reputation: 322
This is the way:
import configparser
config = configparser.ConfigParser()
# The name of your file
config.read('example.ini')
dictionary = {}
for section in config.sections():
dictionary[section] = {}
for option in config.options(section):
dictionary[section][option] = config.get(section, option)
print(dictionary)
The sections
method return a list of all the sections in your config file, the options
method returns all of the options for a section.
Using the get
method of the configparser library you can access all the section-option combo you have loaded from you config file and then place them in a dict with the same schema.
Upvotes: 3