python解析配置文件,包含文件名列表

2024-09-30 16:37:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我想解析一个配置文件,其中包含文件名列表,分为几个部分:

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

我尝试了ConfigParser,但它需要成对的名称值。如何解析这样的文件?在


Tags: 文件名称列表文件名配置文件configparsersection1section2
2条回答

很可能您必须自己实现解析器。在

蓝图:

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)

以下是迭代器/生成器解决方案:

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

相关问题 更多 >