You could easily read them as CSV where = would be the separator.
Here's a csv reader function that additionnaly deals with # comments, and provides a generator.
import csv
def csv_dict_reader(file, has_header=False, skip_comment_char=None, **kwargs):
"""
Reads CSV file into memory
:param file: (str) path to csv file to read
:param has_header: (bool) skip first line
:param skip_comment_char: (str) optional character which, if found on first row, will skip row
:param delimiter: (char) CSV delimiter char
:param fieldnames: (list) CSV field names for dictionnary creation
:param kwargs:
:return: csv object that can be iterated
"""
with open(file) as fp:
csv_data = csv.DictReader(fp, **kwargs)
# Skip header
if has_header:
next(csv_data)
fieldnames = kwargs.get('fieldnames')
for row in csv_data:
# Skip commented out entries
if fieldnames is not None:
if skip_comment_char is not None:
if not row[fieldnames[0]].startswith(skip_comment_char):
yield row
else:
yield row
else:
# list(row)[0] is key from row, works with Python 3.7+
if skip_comment_char is not None:
if not row[list(row)[0]].startswith(skip_comment_char):
yield row
else:
yield row
You can than use that function to read your config.py file, which you can convert to a dict like:
conf = csv_dict_reader('config.py', skip_comment_char='#', delimiter='=', fieldnames=['name', 'value'])
my_dict = {}
for line in conf:
my_dict [line['name']] = line['value']
print(my_dict)
You may have to add .strip() to the names and values in order to remove trailing / ending white spaces.
Bear in mind that reading a python config file this way isn't very elegant.
You might consider using a 'real' config file format, with ConfigParser or so.
[EDIT] Just read your commment that you cannot change the config file format. So at least this should work[/EDIT]