失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > python读取配置文件获取所有键值对_python ConfigParser模块读写配置文件

python读取配置文件获取所有键值对_python ConfigParser模块读写配置文件

时间:2021-04-15 06:21:10

相关推荐

python读取配置文件获取所有键值对_python ConfigParser模块读写配置文件

python2.7中ConfigParser模块对配置文件的读写操作。

一、ConfigParser模块的函数

1.读取

read(filename) 直接读取ini文件内容

sections() 得到所有的section,并以列表的形式返回

options(section) 得到该section的所有option

items(section) 得到该section的所有键值对

get(section,option) 得到section中option的值,返回为string类型

getint(section,option) 得到section中option的值,返回为int类型

2.写入

add_section(section) 添加一个新的section

set( section, option, value) 对section中的option进行设置

conf.write() 写入

二、ConfigParser代码示例

1.配置文件

如果没有配置文件会报错:ConfigParser.NoSectionError: No section[db1]

conn = localhost

port = 3306

user = root

password = 123456

dbname = test

[db2]

conn = localhost

port = 3306

user = root

password = 123456

dbname = test1

2.读取与写入代码#/usr/bin/python

#-*- coding:utf-8 -*-

import ConfigParser

#生成conf对象

conf = ConfigParser.ConfigParser()

#载入配置文件

conf.read('conf.ini')

#===读取===

#列出所有section

print conf.sections() #输出 ['db1', 'db2']

#列出指定section中的option

print conf.options('db1') #输出 ['conn', 'port', 'user', 'password', 'dbname']

#列出指定区的所有键值

print conf.items('db1') #输出 [('conn', 'localhost'), ('port', '3306'), ('user', 'root'), ('password', '123456'), ('dbname', 'test')]

#获取指定section中指定键的值

print conf.get('db1','conn') #输出 localhost

#===写入===

#增加section

conf.add_section('db3')

#设置增加section的option值

conf.set('db3','conn','127.0.0.1')

#更新指定section的option值

conf.set('db3','conn','localhost')

#保存到配置文件

conf.write(open('conf.ini','w'))

如果觉得《python读取配置文件获取所有键值对_python ConfigParser模块读写配置文件》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。