[英]Unable to set a value for an option in a section in .ini file using ConfigParser using Python
I want to update the value of a particular option in a section in '.ini' file. 我想更新“ .ini”文件中某一节中特定选项的值。 I found that 'set' function can be used.
我发现可以使用“设置”功能。 Below is the code that I used.
下面是我使用的代码。 Here, set method is throwing an error "No Section".
在这里,set方法将引发错误“ No Section”。 I tried all upper case and lower case also for the section name.
我也尝试了所有大写和小写的部分名称。 Am i missing anything here?
我在这里想念什么吗?
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
The error is because you are not reading the cfg file before updating the value. 该错误是因为您没有在更新值之前读取cfg文件。
Demo: 演示:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.