简体   繁体   中英

Maintain comments while writing config file in Python

I have a Dictionary like this

dictvalues = {'NAME':'Zara', 'SUBJECT':'English', 'CLASS ':'First'}

I have a config.ini like this

[OPTIONS]

;the following specifies the name of student
NAME = "Zara"
;The following specifies Subject
SUBJECT = "MATHS"

;The Following specifies the Marks

MARKS = "55"

I want to update my config.ini file based on the dictionary

;the following specifies the name of student
NAME = "Zara"
;The following specifies Subject
SUBJECT = "MATHS"

;The Following specifies the Marks

MARKS = "55"


CLASS = "FIRST"

The following code removes the comments.Which are required.

import ConfigParser

data = {'NAME': 'Zara', 'SUBJECT': 'English', 'CLASS': 'First'}

Config = ConfigParser.ConfigParser()
Config.optionxform = str
Config.read("config.ini")


for section in Config.sections():
    for key in data.keys():
        Config.set(section, key,'"{}"'.format(data[key]))

with open("config.ini", 'w+') as f:
    Config.write(f)

如果您将字典定义为"您的输出应符合预期:

 data = {'NAME': '"Zara"', 'SUBJECT': '"English"', 'CLASS': '"First"'}

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