I am trying to iterate through a file which is delimited by = and create a Python dictionary. It has varying line structure and length with: 1.) Some easy to delimit key / value pairs 2.) Some commented lines 3.) Some empty lines 4.) Some multi-lines using \ to indicate continuation.
It is the multi-line part I am struggling to read into the dictionary.
Below is a representation of the file (called file.txt). The multi-lines in the actual file are much longer, but the composition is the same.
# This is a file
name.list={ \
'JOHN' : 'SMITH', \
'PETER' : 'JONES', \
'TED' : 'BAKER', \
'HENRY' : 'FORD', \
'JANE' : 'FONDA' \
}
profile=ABC
tag=123
default=yes
1.) This is the code I have tried:
dict = {}
for file in file_list:
with open(file.txt) as opened_file:
if line.starts.with('#') is False and len(line.strip()) !=0:
try:
key, value = line.strip().split('=', 1)
dict[key.strip()] = value.strip()
except ValueError as e:
print(line)
print(e)
opened_file.close()
print (dict)
2.) The issue is the multi-lines are not being read, and the below message shows in the console and repeats for each multi-line continuation:
not enough values to unpack (expected 2, got 1) 'JOHN' : 'SMITH', \
The only unpacking should be on the = symbol. The intention is not to split anything after that.
3.) The expectation is a dictionary should be created looking something like this:
{'name.list': "{'JOHN' : 'SMITH','PETER' : 'JONES','TED' : 'BAKER','HENRY' : 'FORD','JANE' : 'FONDA'}", 'profile': 'abc', 'tag': '123', 'default': 'yes'}
Any help would be greatly appreciated, thanks.