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

0 投票
2 回答
509 浏览
提问于 2025-04-16 12:34

我想要解析一个配置文件,这个文件里包含了一些文件名,并且这些文件名是分成几个部分的:

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

我试过用ConfigParser,但它需要成对的名字和数值。那我该怎么解析这样的文件呢?

2 个回答

1

这里有一个迭代器/生成器的解决方案:

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

很可能你需要自己实现一个解析器。

大致思路:

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)

撰写回答