在Python中编写配置文件时保持注释

时间:2016-07-18 17:01:29

标签: python parsing config

我有这样的词典

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

我有像这样的config.ini

[OPTIONS]

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

;The Following specifies the Marks

MARKS = "55"

我想根据字典更新我的config.ini文件

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

;The Following specifies the Marks

MARKS = "55"


CLASS = "FIRST"

以下代码删除了评论。这些是必需的。

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)

1 个答案:

答案 0 :(得分:0)

如果您使用"定义字典,则输出应符合预期:

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