如何更新python配置文件中的现有部分? (Python 3.6.6)

时间:2018-09-18 17:49:13

标签: python python-3.x

已经有许多与配置文件有关的问题,其中大多数是用于读写新的Section。我的问题与更新现有部分有关。

我的配置文件rg.cnf

[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")    

运行上面的代码会产生NoSectionError:

configparser.NoSectionError: No section: 'SAVELOCATION2'

应该仅将config.set()与config.add_section()一起使用吗?但这也不起作用,因为它会覆盖整个文件,并且我不想添加任何新部分。

是否有任何方法可以更新配置文件中的部分?

1 个答案:

答案 0 :(得分:1)

您需要先将配置文件加载到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()