繁体   English   中英

在 Python 中使用 ConfigParser 和字典

[英]using ConfigParser and dictionary in Python

我正在尝试使用 ConfigParser 并转换为字典的一些基本 python 脚本。 我正在阅读一个名为“file.cfg”的文件,其中包含三个部分 - 根目录、第一部分、第二部分。 目前,代码读取文件并将文件中的所有内容转换为字典。

我的要求是仅将名为“first”和“second”等的部分转换为字典的键值对。 排除“根”部分及其键值对的最佳方法是什么?

import urllib
import urllib2
import base64
import json
import sys
from ConfigParser import SafeConfigParser

parser = SafeConfigParser()
parser.read('file.cfg')

print parser.get('root', 'auth')

config_dict = {}

for sect in parser.sections():
    config_dict[sect] = {}
    for name, value in parser.items(sect):
        config_dict[sect][name] = value

print config_dict

file.cfg 的内容 -

~]# cat file.cfg

[root]
username = admin
password = admin
auth = http://192.168.1.1/login

[first]
username = pete
password = sEcReT
url = http://192.168.1.1/list

[second]
username = ron
password = SeCrET
url = http://192.168.1.1/status

脚本的输出 -

 ~]# python test4.py 

http://192.168.1.1/login
{'second': {'username': 'ron', 'url': 'http://192.168.1.1/status', 'password': 'SeCrEt'}, 'root': {'username': 'admin', 'password': 'admin', 'auth': 'http://192.168.1.1/login'}, 'first': {'username': 'pete', 'url': 'http://192.168.1.1/list', 'password': 'sEcReT'}}

您可以从parser.sections()中删除root部分,如下所示:

parser.remove_section('root')

此外,您不必遍历每个部分中的每一对。 您可以将它们转换为dict

config_dict = {}
for sect in parser.sections():
    config_dict[sect] = dict(parser.items(sect))

这是一个班轮:

config_dict = {sect: dict(parser.items(sect)) for sect in parser.sections()}

通过比较绕过root部分。

for sect in parser.sections():
    if sect == 'root':
        continue
    config_dict[sect] = {}
    for name, value in parser.items(sect):
        config_dict[sect][name] = value

接受后编辑:

ozgur 的 one liner 是一个更简洁的解决方案。 给我点赞。 如果您不想直接从解析器中删除部分,则可以在之后删除该条目。

config_dict = {sect: dict(parser.items(sect)) for sect in parser.sections()} # ozgur's one-liner
del config_dict['root']

也许有点跑题了,但是 ConfigParser 在存储 int、float 和 booleans 时确实很痛苦。 我更喜欢使用转储到 configparser 中的 dicts。

我还使用函数在 ConfigParser 对象和 dicts 之间进行转换,但它们处理变量类型的变化,所以 ConfigParser 很高兴,因为它请求字符串,我的程序很高兴,因为 'False' 不是 False。

def configparser_to_dict(config: configparser.ConfigParser) -> dict:
    config_dict = {}
    for section in config.sections():
        config_dict[section] = {}
        for key, value in config.items(section):
            # Now try to convert back to original types if possible
            for boolean in ['True', 'False', 'None']:
                if value == boolean:
                    value = bool(boolean)

            # Try to convert to float or int
            try:
                if isinstance(value, str):
                    if '.' in value:
                        value = float(value)
                    else:
                        value = int(value)
            except ValueError:
                pass

            config_dict[section][key] = value

    # Now drop root section if present
    config_dict.pop('root', None)
    return config_dict


def dict_to_configparser(config_dict: dict) -> configparser.ConfigParser:
    config = configparser.ConfigParser()

    for section in config_dict.keys():
        config.add_section(section)
        # Now let's convert all objects to strings so configparser is happy
        for key, value in config_dict[section].items():
            config[section][key] = str(value)

    return config

暂无
暂无

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

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