netimen
netimen

Reputation: 4419

python parse configuration file, containing list of filenames

I would like to parse a config file, containing list of filenames, divided in sections:

[section1]
path11/file11
path12/file12
...
[section2]
path21/file21
..

I tried ConfigParser, but it requires pairs of name-value. How can I parse such a file?

Upvotes: 0

Views: 512

Answers (2)

PaulMcG
PaulMcG

Reputation: 63709

Here is an iterator/generator solution:

data = """\
[section1]
path11/file11
path12/file12
...
[section2]
path21/file21
...""".splitlines()

def sections(it):
    nextkey = next(it)
    fin = False
    while not fin:
        key = nextkey
        body = ['']
        try:
            while not body[-1].startswith('['):
                body.append(next(it))
        except StopIteration:
            fin = True
        else:
            nextkey = body.pop(-1)
        yield key, body[1:]

print dict(sections(iter(data)))

# if reading from a file, do: dict(sections(file('filename.dat')))

Upvotes: 1

user2665694
user2665694

Reputation:

Likely you have to implement the parser on your own.

Blueprint:

key = None
current = list()
for line in file(...):

   if line.startswith('['):
       if key:
           print key, current
       key = line[1:-1]
       current = list()

   else:
       current.append(line)

Upvotes: 1

Related Questions