在python中使用configparser [英] using configparser in python

查看:49
本文介绍了在python中使用configparser的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抱歉,我是 Python 新手,正在尝试使用 ConfigParser 模块.这是一个脚本,用于从 .ini 文件中读取多个部分和值,并将它们打印如下(当前输出).现在,我想将 url、password 的每个值存储到变量中,并使用它们中的每一个来使用 for 循环运行 REST 调用.

Sorry, I am a newbie in Python and trying to work on the ConfigParser module. Here is one script which is used to read multiple sections and values from a .ini file and print them as below (Current output). Now, I would like to store each of these values of url, password into variables and use each of them to run REST call using a for loop.

将每个url"和密码"的值存储到不同的变量中需要进行哪些更改?

What changes are required to store value of each "url" and "password" into different variables?

# cat file.ini

[bugs]
url = http://localhost:1010/bugs/
username = mark
password = SECRET

[wiki]
url = http://localhost:1010/wiki/
username = chris
password = PWD

脚本:-

from ConfigParser import SafeConfigParser

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

for element in parser.sections():
    print 'Section:', element
    print '  Options:', parser.options(element)
    for name, value in parser.items(element):
        print '  %s = %s' % (name, value)
    print

电流输出:-

~]# python parse.py

Section: wiki
  Options: ['url', 'username', 'password']
  url = http://localhost:1010/wiki/
  username = chris
  password = PWD

Section: bugs
  Options: ['url', 'username', 'password']
  url = http://localhost:1010/bugs/
  username = mark
  password = SECRET

推荐答案

from ConfigParser import SafeConfigParser

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

config_dict = {}

for element in parser.sections():
    print 'Section:', element
    config_dict[element] = {}
    print '  Options:', parser.options(element)
    for name, value in parser.items(element):
        print '  %s = %s' % (name, value)
        config_dict[element][name] = value

print config_dict

这篇关于在python中使用configparser的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆