python - 在Python中使用ConfigParser和字典

标签 python

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

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

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()}

关于python - 在Python中使用ConfigParser和字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31801563/

相关文章:

python - 找到在matplotlib中绘制的两条线图的交点

python - 亲戚进口的排序顺序?

python - 限制子类的外键选择

python - float 的日期时间不包括毫秒

python - 如何在 Python 中检查文件是否为 .gz 文件

python + matplotlib : how to make a bar diagram combining 1 bar and 2 bars?

python - 将注释从 Mask-RCNN 数据集格式转换为 COCO 格式

python - 在 PyQT 中如何打开一个可以访问父属性的子窗口?

python - 如何避免在 Django 中导入时访问数据库?

python - 使用生成器作为子流程输入;得到 "I/O operation on closed file"异常