0

Is there a way to parse a config file like this with Python3?

path = .MyAppData
prefer = newer
path = Dokumente

Please don't blame me. ;) I didn't build the software producing config files like this. But they make sense in that special context.

I know ConfigParser and configobj for Python3 but don't see a way to do this.

buhtz
  • 10,774
  • 18
  • 76
  • 149

1 Answers1

2

The ConfigParser initialiser supports the strict=False argument, which allows duplicates. But which value is retained in that case isn't mentioned in the documentation as far as I can tell.

One simple solution is to convert the lines into a dictionary yourself;

In [1]: txt = '''path = .MyAppData
   ...: prefer = newer
   ...: path = Dokumente'''

In [2]: txt.splitlines()
Out[2]: ['path = .MyAppData', 'prefer = newer', 'path = Dokumente']

(After splitting the text in lines, you might want to filter out comments and empty lines.)

In [3]: [ln.split('=') for ln in txt.splitlines()]
Out[3]: [['path ', ' .MyAppData'], ['prefer ', ' newer'], ['path ', ' Dokumente']]

In [4]: vars = [ln.split('=') for ln in txt.splitlines()]

(At this point you might want to add a filter for the inner lists so that you only have lists of length 2, indicating a succesfull split.)

In [5]: {a.strip(): b.strip() for a, b in vars}
Out[5]: {'path': 'Dokumente', 'prefer': 'newer'}

In the dict comprehension (In [5]), later assignments will override earlier ones.

Of course, if prefer = older, you'd have to reverse the lines before the dict comprehension.

Roland Smith
  • 42,427
  • 3
  • 64
  • 94