【问题标题】:How to preserve keys with capital letters read from a config-file with configparser? [duplicate]如何使用 configparser 保存从配置文件中读取的大写字母键? [复制]
【发布时间】:2016-09-07 13:43:55
【问题描述】:

使用 python 的configparser 包读取配置文件时,所有键名都是小写字符串。有人知道如何阅读保留大写和大写单词的字符串吗?

例如:

$cat config.cfg 
[DEFAULT]
Key_1 = SomeWord
KEY_2 = Another Word

$ python3
>>> from configparser import ConfigParser
>>> cf = ConfigParser()
>>> cf.read('./config.cfg')
['./config.cfg']
>>> print(cf.defaults())
OrderedDict([('key_1', 'SomeWord'), ('key_2', 'Another Word')])

感谢您的帮助!

【问题讨论】:

  • 如果你能解释的更详细,会有更多的答案。
  • 抱歉重复了..我没有想到“case”这个词..^.^

标签: python python-3.x configparser


【解决方案1】:

是的,在读/写操作期间,所有键都会自动转换为小写。这在the Quick Start section of the configparser docs的最后一句中提到了。

要不产生这种效果,您可以将解析器的optionxform(可调用)设置为简单地返回option,而不是将其转换为小写:

>>> from configparser import ConfigParser
>>> c = ConfigParser()
>>> c.optionxform = lambda option: option
>>> c.read('./config.cfg')
['./config.cfg']

现在键按定义保留:

>>> c.defaults()
OrderedDict([('Key_1', 'SomeWord'), ('KEY_2', 'Another Word')])

当然,您可以根据自己的喜好对其进行自定义,例如,如果您希望所有键都为大写,您可以在 optionxform 中设置:

>>> cf = ConfigParser()
>>> cf.optionxform = lambda option: option.upper()
>>> cf.read('./config.cfg')
['./config.cfg']
>>> cf.defaults()
OrderedDict([('KEY_1', 'SomeWord'), ('KEY_2', 'Another Word')])

【讨论】:

    猜你喜欢
    • 2021-01-13
    • 2013-10-21
    • 1970-01-01
    • 2019-12-16
    • 2012-03-06
    • 2015-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多