Python之ConfigParser读取配置文件信息

参考:http://www.cnblogs.com/victorwu/p/5762931.html

在项目过程中,需要设置各种IP和端口号信息等,如果每次都在源程序中更改会很麻烦,因此将需要修改的参数写在配置文件中,每次只需修改配置文件,就可以实现同样的目的。Python 标准库的 ConfigParser 模块提供一套 API 来读取和操作配置文件。因此在程序开始位置要导入该模块

import ConfigParser

配置文件的格式

a) 配置文件中包含一个或多个 section, 每个 section 有自己的 option;

b) section 用 [sect_name] 表示,每个option是一个键值对,使用分隔符 = 或 : 隔开;

c) 在 option 分隔符两端的空格会被忽略掉

d) 配置文件使用 # 和 ; 注释

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

# database source
[db]
host = 127.0.0.1
port = 3306
user = root
pass = root
 
# ssh
[ssh]
host = 192.168.1.101
user = huey
pass = huey

ConfigParser 的基本操作

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

cp = ConfigParser.SafeConfigParser()
cp.read('myapp.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.1.101'), ('user', 'huey'), ('pass', 'huey')]

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.1.101

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.1.102')

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('myapp.conf', 'w'))
cp.write(sys.stdout)

Unicode 编码的配置

配置文件如果包含 Unicode 编码的数据,需要使用 codecs 模块以合适的编码打开配置文件。

myapp.conf

[msg]
hello = 你好

config_parser_unicode.py

import ConfigParser
import codecs

cp = ConfigParser.SafeConfigParser()
with codecs.open('myapp.conf', 'r', encoding='utf-8') as f:
    cp.readfp(f)

print cp.get('msg', 'hello')

猜你喜欢

转载自blog.csdn.net/zong596568821xp/article/details/80971645