【问题标题】:Duplicate section when adding a new option configparser添加新选项 configparser 时出现重复部分
【发布时间】:2018-09-11 14:49:54
【问题描述】:

当我向一个部分添加新选项并将文件写入配置时,它似乎总是复制该部分并使用新选项添加​​新选项。

理想情况下,我想避免这种情况,并且只有一个部分,我该如何实现?

示例出现

config.add_section("Install")
config.set("Install", "apt_installer", "True")
cfile = open("file.cfg", "w")
config.write(cfile)
cfile.close()

config.read("file.cfg")
config.set("Install", "deb_installer", "True")
cfile = open("file.cfg", "a")
config.write(cfile)
cfile.close()

当您打开 file.cfg 时,它会安装两次,一次使用 apt_installer,另一次使用 apt_installer 和 deb_installer。任何人都可以提供任何建议,我将不胜感激。

【问题讨论】:

    标签: python python-3.x configparser


    【解决方案1】:

    我认为这里的问题是您以append 模式打开文件。换行试试:

    cfile = open("file.cfg", "a")
    

    cfile = open("file.cfg", "w")
    

    您还应该添加以下行:

    import configparser
    
    config = configparser.ConfigParser()
    

    在顶部,以使您的示例正常工作。所以最后你的例子应该是这样的:

    import configparser
    
    config = configparser.ConfigParser()
    config.add_section("Install")
    config.set("Install", "apt_installer", "True")
    cfile = open("file.cfg", "w")
    config.write(cfile)
    cfile.close()
    
    r = config.read("file.cfg")
    
    config.set("Install", "deb_installer", "True")
    cfile = open("file.cfg", "w")
    config.write(cfile)
    cfile.close()
    

    【讨论】:

    • 嗨 Toti08 是的,在对它进行了更多测试之后,这就是问题所在。我在想自己为什么要追加重复它,但我开始理解 configparser 背后的逻辑,从某种意义上说,它正在读取以前的配置信息,然后会重新编写它,这样它就不会丢失。谢谢你。
    猜你喜欢
    • 2017-06-02
    • 1970-01-01
    • 2021-07-08
    • 1970-01-01
    • 2016-04-16
    • 2018-02-20
    • 2013-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多