简体   繁体   English

在 Python 中使用 ConfigParser 和字典

[英]using ConfigParser and dictionary in Python

I am trying some basic python scripts using ConfigParser and converting to a dictionary.我正在尝试使用 ConfigParser 并转换为字典的一些基本 python 脚本。 I am reading a file named "file.cfg" which contains three sections - root, first, second.我正在阅读一个名为“file.cfg”的文件,其中包含三个部分 - 根目录、第一部分、第二部分。 Currently the code reads the file and converts everything within the file to a dictionary.目前,代码读取文件并将文件中的所有内容转换为字典。

My requirement is to convert only sections named "first" and "second" and so on, its key value pair to a dictionary.我的要求是仅将名为“first”和“second”等的部分转换为字典的键值对。 What would be best way of excluding the section "root" and its key value pair?排除“根”部分及其键值对的最佳方法是什么?

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

Contents of file.cfg - 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

Output of the script -脚本的输出 -

 ~]# 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'}}

You can remove root section from parser.sections() as follows:您可以从parser.sections()中删除root部分,如下所示:

parser.remove_section('root')

Also you don't have to iterate over each pair in each section.此外,您不必遍历每个部分中的每一对。 You can just convert them to dict :您可以将它们转换为dict

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

Here is one liner:这是一个班轮:

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

Bypass the root section by comparison.通过比较绕过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

Edit after acceptance:接受后编辑:

ozgur's one liner is a much more concise solution. ozgur 的 one liner 是一个更简洁的解决方案。 Upvote from me.给我点赞。 If you don't feel like removing sections from the parser directly, the entry can be deleted afterwards.如果您不想直接从解析器中删除部分,则可以在之后删除该条目。

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

Maybe a bit off topic, but ConfigParser is a real pain when in comes to store int, floats and booleans.也许有点跑题了,但是 ConfigParser 在存储 int、float 和 booleans 时确实很痛苦。 I prefer using dicts which I dump into configparser.我更喜欢使用转储到 configparser 中的 dicts。

I also use funtcions to convert between ConfigParser objects and dicts, but those deal with variable type changing, so ConfigParser is happy since it requests strings, and my program is happy since 'False' is not False.我还使用函数在 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