无法使用 Python 使用 ConfigParser 为 .ini 文件的部分中的选项设置值

Unable to set a value for an option in a section in .ini file using ConfigParser using Python

我想更新“.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

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