Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何更新python配置文件中的现有节?(Python 3.6.6)_Python_Python 3.x - Fatal编程技术网

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

如何更新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 =

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

我的配置文件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")    
运行上述代码会出现以下错误:

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()