python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python ConfigParser

Python如何使用ConfigParser读取配置文件

作者:迎风而来

这篇文章主要介绍了Python如何使用ConfigParser读取配置文件,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

在项目过程中,需要设置各种IP和端口号信息等,如果每次都在源程序中更改会很麻烦(因为每次都要重启项目重新加载配置信息),因此将需要修改的参数写在配置文件(或者数据库)中,每次只需修改配置文件,就可以实现同样的目的。Python 标准库的 ConfigParser 模块提供一套 API 来读取和操作配置文件。因此在程序开始位置要导入该模块,注意区分是python2还是python3,python3有一些改动

import ConfigParser #python 2.x
import configparser #python 3.x

配置文件的格式

一个简单的配置文件样例 config.conf

# database source
[db]   # 对应的是一个section
host = 127.0.0.1  # 对应的是一个option键值对形式
port = 3306
user = root
pass = root
 
# ssh
[ssh]
host = 192.168.10.111
user = sean
pass = sean

ConfigParser 的基本操作

a) 实例化 ConfigParser 并加载配置文件

cp = ConfigParser.SafeConfigParser()
cp.read('config.conf')

b) 获取 section 列表、option 键列表和 option 键值元组列表

print('all sections:', cp.sections()) # sections: ['db', 'ssh']
print('options of [db]:', cp.options('db')) # options of [db]: ['host', 'port', 'user', 'pass']
print('items of [ssh]:', cp.items('ssh')) # items of [ssh]: [('host', '192.168.10.111'), ('user', 'sean'), ('pass', 'sean')]

c) 读取指定的配置信息

print('host of db:', cp.get('db', 'host')) # host of db: 127.0.0.1
print('host of ssh:', cp.get('ssh', 'host')) # host of ssh: 192.168.10.111

d) 按类型读取配置信息:getint、 getfloat 和 getboolean

print(type(cp.getint('db', 'port'))) # <type 'int'>

e) 判断 option 是否存在

print(cp.has_option('db', 'host')) # True  

f) 设置 option

cp.set('db', 'host','192.168.10.222')

g) 删除 option

cp.remove_option('db', 'host')

h) 判断 section 是否存在

print(cp.has_section('db')) # True

i) 添加 section

cp.add_section('new_sect')

j) 删除 section

cp.remove_section('db')

k) 保存配置,set、 remove_option、 add_section 和 remove_section 等操作并不会修改配置文件,write 方法可以将 ConfigParser 对象的配置写到文件中

cp.write(open('config.conf', 'w'))
cp.write(sys.stdout)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文