gpt4 book ai didi

python - ConfigParser 获取所有具有重复项的键

转载 作者:太空宇宙 更新时间:2023-11-03 15:47:19 27 4
gpt4 key购买 nike

ini 文件:

[main]
key_1=1
key_2=2
key_1=3

Python:

config_parser = ConfigParser()
config_parser.optionxform = str
config_parser.read('config.ini')
for section in config_parser.sections():
for key in dict(config_parser.items(section)):
print key

结果:

key_1
key_2

预期结果:

key_1
key_2
key_1

如何达到这样的结果?

最佳答案

这是 Python 2 中配置解析器工作方式的问题。键值对被转换成字典。这意味着每个键必须是唯一的。如果您有多个键,则“最后一个值获胜”。

在 Python 3.5 中尝试您的示例,会出现以下错误消息:

DuplicateOptionError: While reading from 'config.ini' [line  4]: 
option 'key_1' in section 'main' already exists

所以不要多次使用同一个 key 。

幸运的是,Python 2 有一个向后移植版本。只需:

pip install configparser 

This library brings the updated configparser from Python 3.5 to Python 2.6-3.5.

现在,像这样使用:

from configparser import ConfigParser

这就是 Wikipedia关于重复的说法:

Duplicate names

Most implementations only support having one property with a given name in a section. The second occurrence of a property name may cause an abort, it may be ignored (and the value discarded), or it may override the first occurrence (with the first value discarded). Some programs use duplicate property names to implement multi-valued properties.

Interpretation of multiple section declarations with the same name also varies. In some implementations, duplicate sections simply merge their properties together, as if they occurred contiguously. Others may abort, or ignore some aspect of the INI file.

关于python - ConfigParser 获取所有具有重复项的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41640804/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com