如何更新python配置文件中的现有节?(Python 3.6.6)
与配置文件相关的问题已经很多了,其中大多数是用于读写新的部分。我的问题与更新现有部分有关 我的配置文件rg.cnf如何更新python配置文件中的现有节?(Python 3.6.6),python,python-3.x,Python,Python 3.x,与配置文件相关的问题已经很多了,其中大多数是用于读写新的部分。我的问题与更新现有部分有关 我的配置文件rg.cnf [SAVELOCATION1] outputpath1 = TestingPath [SAVELOCATION2] outputpath2 = TestingPath 更新配置文件的代码: def updateConfigFile(fileName, textdata): config = configparser.ConfigParser() cnfFile =
[SAVELOCATION1]
outputpath1 = TestingPath
[SAVELOCATION2]
outputpath2 = TestingPath
更新配置文件的代码:
def updateConfigFile(fileName, textdata):
config = configparser.ConfigParser()
cnfFile = open(fileName, "w")
config.set("SAVELOCATION2","outputpath2",textdata)
config.write(cnfFile)
cnfFile.close()
将上述方法调用为:
updateConfigFile("rg.cnf","TestingPath2")
运行上述代码会出现以下错误:
configparser.NoSectionError: No section: 'SAVELOCATION2'
config.set()是否应仅与config.add_section()一起使用?但这也不起作用,因为它覆盖了整个文件,我不想添加任何新的部分
是否有任何方法更新配置文件中的节?您需要将配置文件加载到
ConfigParser
中,然后才能对其进行编辑:
def updateConfigFile(fileName, textdata):
config = configparser.ConfigParser()
config.read(fileName) # Add this line
cnfFile = open(fileName, "w")
config.set("SAVELOCATION2","outputpath2",textdata)
config.write(cnfFile)
cnfFile.close()