开发者

python parse configuration file, containing list of filenames

开发者 https://www.devze.com 2023-02-13 19:05 出处:网络
I would like to parse a config file, containing list of filenames, divided in sections: [section1] path11/file11

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

[section1]
path11/file11
path12/file12
...
[section2]
path21/file21
..
开发者_JAVA技巧

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


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)


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')))
0

精彩评论

暂无评论...
验证码 换一张
取 消