Kristof Pal
Kristof Pal

Reputation: 1026

Nicely parsing a multiline config file in python

I need a config file to generate my scripts.

[PATHS]
elements = elementA,elementB,elementC,elementD,elementE,elementF,elementG,elementH,elementJ,elementK

As you notice after a point the line gets too long. I can not keep track of the elements written in it and does not look nice at all.

In my script I do the following to read elements:

elements = config["PATHS"]["elements"].split(",")

Is there a nicer way to handle this? I would prefer something that includes linebreak and tabs, for example:

[PATHS]
elements = 
    - elementA
    - elementB
    - elementC
    - elementD
    - elementE
    - elementF
    - elementG
    - elementH
    - elementJ
    - elementK

Any suggestions from the more experienced are welcome too.

I tried splitting with .split("\n\t\t- ") but did not do the work


print("1",config["PATHS"]["elements"])

1 
- elementA
- elementB
- elementC


print("2",config["PATHS"]["elements"].strip())
2 - elementA
- elementB
- elementC


print("3",config["PATHS"]["elements"].strip().split('\n'))
3 ['- elementA', '- elementB', '- elementC']

Upvotes: 2

Views: 2526

Answers (1)

Robᵩ
Robᵩ

Reputation: 168616

This might do what you want:

elements = [
    element.strip(' -')
    for element in config["PATHS"]["elements"].strip().split('\n')]

Upvotes: 3

Related Questions