Parsing a file with hierarchical structure in Python
- by Kevin Stargel
I'm trying to parse the output from a tool into a data structure but I'm having some difficulty getting things right. The file looks like this:
Fruits
Apple
Auxiliary
Core
Extras
Banana
Something
Coconut
Vegetables
Eggplant
Rutabaga
You can see that top-level items are indented by one space, and items beneath that are indented by two spaces for each level. The items are also in alphabetical order.
How do I turn the file into a Python list that's something like ["Fruits", "Fruits/Apple", "Fruits/Banana", ..., "Vegetables", "Vegetables/Eggplant", "Vegetables/Rutabaga"]?