Python之配置文件模块 ConfigParser
2016-12-25 12:50
555 查看
写项目肯定用的到配置文件,这次学习一下python中的配置文件模块 ConfigParser
安装就不说了,pip一下即可,直接来个实例
配置文件 project.conf
脚本 project.py
总结方法:
转载自:http://www.cnblogs.com/cmsd/p/3877761.html
安装就不说了,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')) #保存到配置文件
转载自:http://www.cnblogs.com/cmsd/p/3877761.html
相关文章推荐
- python中用Configparser模块解析配置文件
- Python使用自带的ConfigParser模块读写ini配置文件
- Python模块之ConfigParser - 读写配置文件
- Python Configparser模块读取、写入配置文件
- 用ConfigParser模块读写配置文件——Python
- Python模块之ConfigParser - 读写配置文件
- Python模块之ConfigParser - 读写配置文件
- 【Python】配置文件解析模块ConfigParser使用实例
- python中利用ConfigParser模块读取配置文件
- python模块之ConfigParser:解析配置文件模块
- Python自动化测试 -ConfigParser模块读写配置文件
- python ConfigParser模块 配置文件解析
- 使用python的ConfigParser模块方便的读取配置文件
- python模块之ConfigParser: 用python解析配置文件
- [zz]python模块之ConfigParser: 用python解析配置文件
- Python - ConfigParser模块读写配置文件
- python3配置文件模块configparser.ConfigParser
- Python模块之ConfigParser - 读写配置文件
- Python配置文件解析模块ConfigParser使用实例
- Python模块:配置文件解析器configparser