代码之家  ›  专栏  ›  技术社区  ›  user8823315

无法为中的节中的选项设置值。使用Python的ConfigParser的ini文件

  •  0
  • user8823315  · 技术社区  · 6 年前

    我想更新“”中某节中特定选项的值。ini文件。我发现可以使用“set”函数。下面是我使用的代码。这里,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
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Rakesh    6 年前

    错误是因为在更新值之前没有读取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)