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

标签 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() 一起使用吗?但这也不起作用,因为它会覆盖整个文件,而且我不想添加任何新部分。

有什么方法可以更新配置文件中的部分吗?

最佳答案

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

相关文章:

python - 获取行中条件匹配的列名

python - 如何让 groupby() 组在条件下加倍?

python - 如何创建多列索引数据框以及如何为每组值绘制图表

python - 在胡言乱语中以美丽的结果进行抓取

python - 从数据帧的不同部分减去两个系列

python - 将列拆分为多列,在 Pandas 中具有唯一值

python - Python While 循环的问题

python - 如何从特定的 Django 模型实例中获取所有 RelatedManagers?

python - 如何将数据从 google drive 导入 google colab?

python - 如何避免在 Django 中导入时访问数据库?