python 配置文件解析代码_python学习笔记3-解析配置文件ConfigParser模块

配置文件内容:

[db]

db_host=127.0.0.1

db_port=3306

db_user=root

db_pass=password

[concurrent]

thread=10

processor=20

如果遵循以上格式,那么就可以用python的ConfigParser模块。

#!/usr/bin/python

# Filename: parse_module.py

import ConfigParser

filename = 'my.conf'

parse = ConfigParser.ConfigParser()

parse.read(filename)

sections = parse.sections()

for i in sections:

options = parse.options(i)

values = parse.items(i)

print "Section is %s " % i

print "Options are %s " % options

print "Values are %s " % values

输出:

Section is db

Options are ['db_host', 'db_port', 'db_user', 'db_pass']

Values are [('db_host', '127.0.0.1'), ('db_port', '3306'), ('db_user', 'root'), ('db_pass', 'password')]

Section is concurrent

Options are ['thread', 'processor']

Values are [('thread', '10'), ('processor', '20')]

但是如果配置文件中,parameter选项中含有[],则无法用此模块进行解析。。因此当试用python作为开发语言时,配置文件的格式可以选择符合configparser模块的格式。。。

下面的配置就无法使用configparser模块. 会将含有[]的部分当作section来解析。。。。

[db]

host[0]=127.0.0.1

host[1] = 192.168.1.123

db_port=3306

db_user=root

db_pass=password

[concurrent]

thread=10

processor=20

使用configparser模块解析配置文件时,发现的问题:

参数名称的大写全部会转换为小写。

参数名称不能含有[,]

如果含有多个名字相同的section时,会以最后一个section为准。

一个简单的读配置文件的代码,其中section部分相当与忽略了,而返回一个包含所有的参数的dict。

#!/usr/bin/python

# Filename: readConf.py

import ConfigParser

cofile = 'test2.properties'

def read_config_file(filename):

'''Read_config_file(filename)

this function is used for parse the config file'''

data = {}

config = ConfigParser.ConfigParser()

try:

with open(filename,'r') as confile:

config.readfp(confile)

#config.read(filename)

for i in config.sections():

for (key, value) in config.items(i):

data[key] = value

return data

except Exception:

print "Open file error."

p = read_config_file(cofile)

如果有更简单或者更清晰的代码,欢迎大家指正。。。。。

还是发现了一个问题,如果不同的section中含有相同参数名字的参数,那个上面这个解析将无法判断出参数来自哪个section。

例如,myslq的配置文件中,client section和mysqld section中都含有socket和port这两个参数。如果用上面的代码,则无法判断哪个dict中的两个socket和port分别来自哪个section。。。

这样存放了之后,dict中的元素的先后顺序,和添加的顺序有不同。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值