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

python解析配置文件,包含文件名列表,python,parsing,config,Python,Parsing,Config,我想解析一个包含文件名列表的配置文件,该文件分为几个部分: [section1] path11/file11 path12/file12 ... [section2] path21/file21 .. 我尝试了ConfigParser,但它需要名称-值对。如何解析这样的文件?您可能必须自己实现解析器 蓝图: key = None current = list() for line in file(...): if line.startswith('['): if key:

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

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

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

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

蓝图:

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

您希望从分析中得到什么结果?是否希望每个部分都有一个列表,并将路径/文件字符串作为列表的元素?