您的位置:首页 > 编程语言 > Python开发

Python模块之ConfigParser - 读写配置文件

2017-05-25 08:46 726 查看
原文:http://www.cnblogs.com/victorwu/p/5762931.html

注:从配置文件中读取到的数据格式都为str

配置文件的格式

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]
host = 192.168.1.101
user = huey
pass = huey

读取配置文件

# 实例化 ConfigParser
cp = ConfigParser.SafeConfigParser()
# 加载配置文件
cp.read('myapp.conf')


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

# 获取配置文件中所有section,返回的结果为list类型
cp.sections() # sections: ['db', 'ssh']
# 获取配置文件中sections=db的option的键
cp.options('db')  # [db]: ['host', 'port', 'user', 'pass']
# 获取配置文件中sections=ssh的键值对
cp.items('ssh') # [('host', '192.168.1.101'), ('user', 'huey'), ('pass', 'huey')]


读取指定的配置信息

# 判断sectino=db是否存在
cp.has_section('db')
# 判断 section=db 下的option=host 是否存在
cp.has_option('db', 'host')
# 添加 section=new_sect
cp.add_section('new_sect')
# 读取指定的配置信息
cp.get('db', 'host') # db: 127.0.0.1
# 设置 section=db下的host=192.168.1.102
cp.set('db', 'host','192.168.1.102')
# 删除 section=db
cp.remove_section('db')
#  删除 section=db下的option=hsot
cp.remove_option('db', 'host')

注:以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')
DEFAULT section

如果配置文件中存在一个名为 DEFAULT 的 section,那么其他 section 会扩展它的 option 并且可以覆盖它的 option

[DEFAULT]
host = 127.0.0.1
port = 3306

[db_root]
user = root
pass = root

[db_huey]
host = 192.168.1.101
user = huey
pass = huey


----------------------------------------------------
print cp.get('db_root', 'host')    # 127.0.0.1
print cp.get('db_huey', 'host')    # 192.168.1.101

插值 Interpolation

SafeConfigParser 提供了插值的特性来结合数据

[DEFAULT]
url = %(protocol)s://%(server)s:%(port)s/

[http]
protocol = http
server = localhost
port = 8080

[ftp]
url = %(protocol)s://%(server)s/
protocol = ftp
server = 192.168.1.102


-------------------------------------------
import ConfigParser

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

print cp.get('http', 'url')    # http://localhost:8080/ print cp.get('ftp', 'url')     # ftp://192.168.1.102/[/code] 
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: