简体   繁体   English

使用python“ ConfigParser”编辑ini文件会将所有ini条目替换为较低的键

[英]Editing ini file using python “ConfigParser” will replace all ini entries to lower keys

The code snippet below can edit an ini file, but will replace all ini entries to lower case: 下面的代码段可以编辑ini文件,但会将所有ini条目替换为小写:

config = ConfigParser.RawConfigParser()
config.read("test.ini")
config.set("GENERAL", "OptionEntry4", "100")
with open("test.ini", 'w') as configfile:
    config.write(configfile)

ini file before edit: 编辑前的ini文件:

[GENERAL] [一般]
OptionEntry1 = 10 OptionEntry1 = 10
OptionEntry2 = 20 OptionEntry2 = 20
OptionEntry3 = 30 OptionEntry3 = 30
OptionEntry4 = 40 OptionEntry4 = 40
OptionEntry5 = 50 OptionEntry5 = 50

ini file after edit: 编辑后的ini文件:

[GENERAL] [一般]
optionentry1 = 10 optionentry1 = 10
optionentry2 = 20 optionentry2 = 20
optionentry3 = 30 optionentry3 = 30
optionentry4 = 100 optionentry4 = 100
optionentry5 = 50 optionentry5 = 50

according to the documentation : "All option names are passed through the optionxform() method. Its default implementation converts option names to lower case." 根据文档:“所有选项名称均通过optionxform()方法传递。其默认实现将选项名称转换为小写。”

config = ConfigParser.RawConfigParser()
config.optionxform = str

should fix it. 应该修复它。

config = ConfigParser.RawConfigParser()
config.optionxform = str
config.read("test.ini")
config.set("GENERAL", "OptionEntry4", "100")
with open("test.ini", 'w') as configfile:
    config.write(configfile)

Read the doc: https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform 阅读文档: https : //docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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