2

I'm working on a script which scans a series of config files in different directories to make sure that they have a particular value: In this case, they must have the section MySection, which must have the option Opt1, which must not be equal to 0. If it passes all these tests, the file is OK.

The problem I'm having, though, is that ConfigParser appears to "remember" all the files it scans, so if the first file it scans contains Opt1, every successive file will test positive for Opt1 as well... even if the successive files are completely blank. I'm guessing ConfigParser has some sort of cache which needs to be cleared before reading each file? Any help is much appreciated.

Here's the code:

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()
John Allie
  • 245
  • 2
  • 10

1 Answers1

3

The code reuse the same ConfigParser object (parser) multiple time. It does remember the configuration.

Create ConfigParser object each time you read new file.

def repair(file,fsplit):
    parser = configparser.ConfigParser()
    parser.optionxform = str
    with open(file) as f:
        parser.read_file(f)
    ...
falsetru
  • 357,413
  • 63
  • 732
  • 636