[英]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.