2011-02-26 66 views
0

含有名單我想解析一個配置文件,其中包含文件名,在部分分的名單:蟒蛇解析配置文件,文件名

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

我試過ConfigParser,但它需要對名稱的價值。我如何解析這樣的文件?

+0

你從剖析想要什麼樣的結果?你是否希望每個部分都有一個列表,路徑/文件字符串作爲列表的元素? – 2011-02-26 09:51:43

回答

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

這裏是一個迭代器/發電機解決方案:

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