简体   繁体   中英

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']

This might do what you want:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM