python学习笔记3-解析配置文件ConfigParser模块
来源:互联网 发布:中博装饰怎么样 知乎 编辑:程序博客网 时间:2024/06/03 22:42
配置文件内容:
[db]db_host=127.0.0.1db_port=3306db_user=rootdb_pass=password[concurrent]thread=10processor=20
如果遵循以上格式,那么就可以用python的ConfigParser模块。
#!/usr/bin/python# Filename: parse_module.pyimport ConfigParserfilename = '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.1host[1] = 192.168.1.123db_port=3306db_user=rootdb_pass=password[concurrent]thread=10processor=20
使用configparser模块解析配置文件时,发现的问题:
- 参数名称的大写全部会转换为小写。
- 参数名称不能含有[,]
- 如果含有多个名字相同的section时,会以最后一个section为准。
一个简单的读配置文件的代码,其中section部分相当与忽略了,而返回一个包含所有的参数的dict。
#!/usr/bin/python# Filename: readConf.pyimport ConfigParsercofile = '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中的元素的先后顺序,和添加的顺序有不同。
- python学习笔记3-解析配置文件ConfigParser模块
- ConfigParser模块学习: 用python解析配置文件
- python模块之ConfigParser:解析配置文件模块
- Python模块:配置文件解析器configparser
- Python之配置文件解析模块ConfigParser简介
- Python 解析配置文件 (ConfigParser)模块
- 【Python】配置文件解析模块ConfigParser使用实例
- 解析配置文件ConfigParser模块
- PYTHON 配置文件模块 ConfigParser
- Python 配置文件 ConfigParser 模块
- [Python]ConfigParser解析配置文件
- python模块之ConfigParser: 用python解析配置文件
- python模块之ConfigParser: 用python解析配置文件
- 使用ConfigParser模块解析配置文件
- python-ConfigParser模块【读写配置文件】
- 【ConfigParser模块】Python处理配置文件
- python-ConfigParser模块【读写配置文件】
- python-ConfigParser模块【读写配置文件】
- apk反编译获取完整源码 及 apk反编译后的处理
- Xmanager 3.0 运行失败的解决方法
- mysql_root密码重置
- mongoDB的连接池问题
- 关于数据库连接字符串问题(第五部分连接access-2007)
- python学习笔记3-解析配置文件ConfigParser模块
- C#编码规范
- Word文档每次保存时自动更新修改日期
- Jquery基础知识
- HTML5中Canvas与SVG的比较
- 拓扑排序
- JS file清空
- VMware运行Ubuntu 三种网络连接方式:bridge、NAT、Host-Only的区别详解
- .NET平台的AutoCAD二次开发