Skip to main content
 首页 » 编程设计

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

2024年11月01日10jyk

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

不过,我遇到的问题是 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) 
    ...