使用ConfigParser模块解析普通文件

ConfigParser模块是Python中专门用来读取配置文件的包。配置文件的格式如下:中括号“[ ]”内包含的为section。section 下面为类似于key-value 的配置内容:

# build.ini
[db]
db_host = 127.0.0.1
db_port = 22
db_user = root
db_pass = 1234

[handle]
handle_thread = 10
handle_processor = 20
常见的处理方法如下:

import ConfigParser as cp

### 初始化实例,并读取配置文件
cf = cp.ConfigParser()
cf.read("build.ini")

### 获取所有sections
st = cf.sections()
print 'section:', st

### 获取指定sections的options
op = cf.options("db")
print 'options:', op

### 获取指定section的配置信息
vl = cf.items("db")
print 'db_k==v:', vl

### 按照类型读取指定section的option信息
# get()           //-->获取字符串变量
# getint()        //-->获取整数型变量
# getfloat()      //-->获取浮点型变量
# getboolean()    //-->获取布尔型变量
db_host = cf.get("db", "db_host")
db_port = cf.getint("db", "db_port")
db_user = cf.get("db", "db_user")
db_pass = cf.get("db", "db_pass")
print "db_host:", db_host
print "db_port:", db_port
print "db_user:", db_user
print "db_pass:", db_pass

### 设置某个option的值,用w来保存设置
cf.set("db", "db_pass", "4321")
cf.write(open("build.ini", "w"))

### 添加一个section,用w来保存设置
cf.add_section("system")
cf.set("system", "system_os", "Linux")
cf.set("system", "system_admin", "root")
cf.set("system", "system_version", "4.11.12")
cf.write(open("build.ini", "w"))

### 移除section或者option,用w来保存设置
cf.remove_option("system","system_os")
cf.remove_section("system")
cf.write(open("build.ini", "w"))
上面的输出大概如下

section: ['db', 'handle']
options: ['db_host', 'db_port', 'db_user', 'db_pass']
db_k==v: [('db_host', '127.0.0.1'), ('db_port', '22'), ('db_user', 'root'), ('db_pass', '4321')]
db_host: 127.0.0.1
db_port: 22
db_user: root
db_pass: 4321
如果配置文件不是上面标准的格式,要如何解析

# 配置文件名:build.ini
db_host = 127.0.0.1
db_port = 22
db_user = root
db_pass = 4321
一般能想到的处理办法:

user = ''
port = 0
with open(r'build.ini','r') as fd:
    for line in fd:
        if line.split('=')[0].strip() == 'db_user':
            user = line.split('=')[1]
        if line.split('=')[0].strip() == 'db_port':
            port = line.split('=')[1]
print 'user: %s port: %s' % (user, port)
上面的配置文件build.ini不是标准的ini,缺少section,简单处理下,就是自己在脚本中添加个[db],然后再处理!

import ConfigParser as cp
import StringIO

cfg = cp.RawConfigParser()
cfg.readfp(StringIO.StringIO('[db]\n' + open('build.ini').read()))
user = cfg.get('db', 'db_user')
port = cfg.get('db', 'db_port')
print 'user: ', user
print 'port: ', port
经过上面的处理,同样能达到上面的效果,而且代码简洁,输出漂亮,而且更Pythonic







你可能感兴趣的:(【编程语言】,【数据仓库】,【项目管理】)