已经有很多与配置文件相关的问题,其中大多数是关于读取和写入新的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() 一起使用吗?但这也不起作用,因为它会覆盖整个文件,而且我不想添加任何新部分。
有什么方法可以更新配置文件中的部分吗?
最佳答案
您需要将配置文件加载到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()
关于python - 如何更新 python 配置文件中的现有部分? (Python 3.6.6),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52392102/