有没有办法让ConfigParser'没有'返回一个列表

时间:2014-08-20 15:39:28

标签: python configparser

我试图让ConfigParser从包含多个部分的文件中读取。然后我会让我的代码用for循环遍历每个部分,并将当前可用的密钥分配给变量。

从那里,我调用re.search来搜索单独文件中的当前可用密钥。

这里有点想法(因为我并不喜欢这种语言)

import re
import sys
import ConfigParser

inputfile = raw_input("Enter config file: ")
scanfile = raw_input("Enter name of file to scan through: ")
searchfile = open(scanfile,'r')
config = config.ConfigParser(allow_no_value=True)
config.read(inputfile)
for ch in config.sections():
  keys = config.options(ch)
  person = ch
  for line in scanfile:
   if re.search(keys,line):
     outfile = open(person,'w')  
     print >> outfile,line

但是,configparser返回一个破坏re.search的列表。有没有办法让它返回一个元组,或者更好的是,只有没有[]的裸选项?

是否还有另一个模块也可以搜索(find()不适用于我尝试做的事情)。

谢谢

1 个答案:

答案 0 :(得分:1)

如果要检查键列表中的任何键是否在行中:

import re
import sys
import ConfigParser
inputfile = raw_input("Enter config file: ")
scanfile = raw_input("Enter name of file to scan through: ")
searchfile = open(scanfile,'r')
config = ConfigParser.ConfigParser(allow_no_value=True)
config.read(inputfile)
for ch in config.sections():
  keys = set(config.options(ch))
  person = ch
  for line in searchfile: # iterate over file object not the string
      if any(k in keys for k in line.split()):
         outfile = open(person,'w')
         print >> outfile,line
searchfile.close()
outfile.close()

使用with并对您的变量命名方式进行一些更改:

input_file = raw_input("Enter config file: ")
scan_file = raw_input("Enter name of file to scan through: ")
config = ConfigParser.ConfigParser(allow_no_value=True)
config.read(input_file)
with open(scan_file, 'r') as search_file:: # with closes your files automatically
    for person in config.sections():
        keys = set(config.options(person))
        for line in search_file:
            if any(k in keys for k in line.split()): # check if any key is in the line
                with open(person, 'w') as out_file:
                   out_file.write(line)