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

2024-03-28 13:32:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个脚本,它扫描不同目录中的一系列配置文件,以确保它们具有特定的值:在本例中,它们必须具有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()

Tags: 文件thepathinfromparserifos
1条回答
网友
1楼 · 发布于 2024-03-28 13:32:33

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

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

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

相关问题 更多 >