Python:configparser记住以前文件中的值

Python:configparser记住以前文件中的值,python,configparser,Python,Configparser,我正在编写一个脚本,该脚本扫描不同目录中的一系列配置文件,以确保它们具有特定的值:在本例中,它们必须具有MySection部分,该部分必须具有Opt1选项,该选项不得等于0。如果它通过了所有这些测试,则该文件是正常的 不过,我遇到的问题是,ConfigParser似乎“记住”了它扫描的所有文件,因此,如果它扫描的第一个文件包含Opt1,则每个后续文件的Opt1测试结果也将为阳性。。。即使连续文件完全为空。我猜ConfigParser有某种缓存,在读取每个文件之前需要清除它?非常感谢您的帮助 代码

我正在编写一个脚本,该脚本扫描不同目录中的一系列配置文件,以确保它们具有特定的值:在本例中,它们必须具有
MySection
部分,该部分必须具有
Opt1
选项,该选项不得等于0。如果它通过了所有这些测试,则该文件是正常的

不过,我遇到的问题是,ConfigParser似乎“记住”了它扫描的所有文件,因此,如果它扫描的第一个文件包含
Opt1
,则每个后续文件的
Opt1
测试结果也将为阳性。。。即使连续文件完全为空。我猜ConfigParser有某种缓存,在读取每个文件之前需要清除它?非常感谢您的帮助

代码如下:

import configparser
import os
from collections import OrderedDict

parser=configparser.ConfigParser()
parser.optionxform=str

workdir=os.path.dirname(os.path.realpath(__file__))+"/"

def GetAllDirs():
    #Get All Directories in Working Directory
    dirs = [o for o in os.listdir(workdir) if os.path.isdir(os.path.join(workdir,o)) ]
    for d in dirs:
        GetAllTGM(workdir+d)

def GetAllTGM(dir):
    #List all the INI files in a directory
    files= [f for f in os.listdir(dir) if os.path.isfile(os.path.join(dir,f)) ]
    for f in files:
        fa = dir+"/"+f
        fs = split(fa)
        if fs[1]=='.ini' or fs[1]=='.INI':
            repair(fa,fs)
        else:
            pass

def split(filepath):
    #Split the filepath from the file extension
    return os.path.splitext(filepath)

def getoption(sec,option):
    #Get the value of an option from the file
    return parser.get(sec,option)

def repair(file,fsplit):
    parser.read_file(open(file))
    print("\n"+str(parser.sections()))
    if parser.has_section('MySection'):
    #if section exists
        if parser.has_option('MySection','Opt1'):
        #Check if it has Opt1
            if getoption('MySection','Opt1')=="0":
            #It's bad if Opt1=0
                print("Malformed section in "+str(file))
            else:
            #If Opt1!=0, all is good
                print("Section OK in "+str(file))
        else:
        #It's also bad if Opt1 is not present
            print("Malformed section in "+str(file))
    else:
    #And it's bad if MySection doesn't exist
        print("Section missing from "+str(file))

print("Now Running")
GetAllDirs()

代码多次重用相同的
ConfigParser
对象(
parser
)。它确实记得配置

每次读取新文件时创建
ConfigParser
对象

def repair(file,fsplit):
    parser = configparser.ConfigParser()
    parser.optionxform = str
    with open(file) as f:
        parser.read_file(f)
    ...

为每个文件创建一个新的解析器对象怎么样?很好!谢谢