【问题标题】:Unable to set a value for an option in a section in .ini file using ConfigParser using Python无法使用 Python 使用 ConfigParser 为 .ini 文件中的部分中的选项设置值
【发布时间】:2018-03-12 06:26:28
【问题描述】:

我想更新“.ini”文件中某个部分的特定选项的值。我发现可以使用“设置”功能。下面是我使用的代码。在这里,set 方法抛出错误“No Section”。我也尝试了所有大写和小写的部分名称。我在这里有什么遗漏吗?

section="Section1"

option="code_id"

value="09000033"

configuration = configparser.ConfigParser()

configuration.set(section, option, value)

with open(file, 'wb') as configfile:
   configuration.write(configfile)

这是文件:-

[DEFAULT]

code_id_1= 12321

code_id_2= 565656

code_id_3= 8985655

[Section1]

code_id_1= 564555

code_id_2= 896523

code_id_3= 1452663

【问题讨论】:

    标签: python python-3.x configparser


    【解决方案1】:

    错误是因为您在更新值之前没有读取 cfg 文件。

    演示:

    import ConfigParser
    section="Section1"
    option="code_id"
    value="090000333333339999999"
    
    config = ConfigParser.ConfigParser()
    config.readfp(open(file))   #--->READ FILE
    
    config.set(section, option, value)
    
    with open(file) as configfile:
        config.write(configfile)
    

    【讨论】:

    • 不客气。如果它解决了您的问题,请接受。谢谢
    • 对不起,这是新的!我如何接受ans?它确实解决了我的问题。
    • stackoverflow.com/help/someone-answers。您只需点击答案附近的“打勾”符号
    猜你喜欢
    • 2011-03-27
    • 2015-03-13
    • 2016-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-27
    相关资源
    最近更新 更多