![](/img/trans.png)
[英]Read text file (containing list of Python filenames) and kill Python job if Python file appears in text file
[英]python parse configuration file, containing list of filenames
我想解析一个配置文件,其中包含文件名列表,分为几个部分:
[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')))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.