Python之配置文件模块 ConfigParser

时间:2022-11-05 12:01:38

写项目肯定用的到配置文件,这次学习一下python中的配置文件模块 ConfigParser

安装就不说了,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')) #保存到配置文件