Python之配置文件模块 ConfigParser
2014-07-30 12:56
344 查看
写项目肯定用的到配置文件,这次学习一下python中的配置文件模块 ConfigParser
安装就不说了,pip一下即可,直接来个实例
配置文件 project.conf
脚本 project.py
总结方法:
安装就不说了,pip一下即可,直接来个实例
配置文件 project.conf
[db] host = '127.0.0.1' port = 3306 user = 'root' password = 'redhat' db = 'project' [app] threads = 4 cache_size = 8M [game] speed = 100
脚本 project.py
#!/usr/bin/python #coding: utf-8 import ConfigParser cf = ConfigParser.ConfigParser() cf.read('project.conf') #所有section print cf.sections() #显示某个sections下的选项 print cf.options('db') #键值方式显示section的值 print cf.items('db') #获得某个section的某个选项的值 host = cf.get('db', 'host') print host ##get获得是string格式的,下面获得Int格式的和float格式的 port = cf.getint('db', 'port') print port, type(port) port = cf.getfloat('db', 'port') print port, type(port) ##获得boolean方式的值 play = cf.getboolean('game', 'play') print play ##添加section cf.add_section('redis') print cf.sections() ##添加option cf.set('redis', 'host', '127.0.0.1') print cf.items('redis') ##修改option cf.set('db', 'host', '192.168.1.1') print cf.items('db') ##保存配置文件 cf.write(open('project.conf', 'w'))
总结方法:
read(filename) #读取配置文件 sections() #返回所有section options(section) #返回section中的option items(section) #返回sectiond的键值对 get(section, option) #返回某个section,某个option的值,类型是string getint, getfloat, getboolean 等等返回的只是类型不同 修改配置 add_section(section) #添加section set(section,option,value) #添加或者修改值 write(open(filename,'w')) #保存到配置文件
相关文章推荐
- Python 模块之 ConfigParser: 用 Python 解析配置文件
- Python 配置文件 ConfigParser 模块
- PYTHON 配置文件模块 ConfigParser
- python-配置解析模块configparser-读取配置文件-遍历配置文件
- Python 解析配置文件 (ConfigParser)模块
- 【ConfigParser模块】Python处理配置文件
- python之模块配置文件ConfigParser(在python3中变化较大)
- 详解Python读取配置文件模块ConfigParser
- python下paramiko模块学习之二:利用配置文件登录批量主机
- python模块之ConfigParser: 用python解析配置文件
- Python利用ConfigParser读取配置文件
- [Python]ConfigParser解析配置文件
- python中用Configparser模块解析配置文件
- python 提供INI配置文件的操作 ConfigParser
- python模块之ConfigParser:解析配置文件模块
- ConfigParser模块学习: 用python解析配置文件
- Python的系统管理_11_ConfigParser读取配置文件
- Python模块之: ConfigParser 配置文件读取
- python下paramiko模块学习之二:利用配置文件登录批量主机
- python 读取ini配置文件模块 configobj 介绍