简体   繁体   中英

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. I found that 'set' function can be used. Below is the code that I used. Here, set method is throwing an error "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)

This is the file:-

[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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM