我想解析一个配置文件,其中包含文件名列表,分为几部分:
[section1]
path11/file11
path12/file12
...
[section2]
path21/file21
..
我尝试过ConfigParser,但它需要成对的名称值。我该如何解析这样的文件?
答案 0 :(得分: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)
答案 1 :(得分: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')))