python使用ConfigParse解析配置文件

来源:互联网 发布:人人商城源码下载 编辑:程序博客网 时间:2024/05/16 17:32

1 my.cnf 样板数据

[client]port = 3306user = mysqlpassword = mysql[mysqld]basedir = /usrdatadir = /var/lib/mysqltmdir = /tmpskip-external-locking[mysql]host = 127.0.0.1

2  基本操作

#! /usr/bin/env python#coding:utf-8import ConfigParsercf=ConfigParser.ConfigParser(allow_no_value=True)cf.read('my.cnf')# ==========================读取==================================# 获取client,mysqld print(cf.sections())'''['client', 'mysqld']'''#判断client 是否存在print(cf.has_section('client'))'''True'''#client内容以tuple返回print(cf.items('client'))'''[('prot', '3306'), ('user', 'mysql'), ('password', 'mysql'), ('host', '127.0.0.1')]'''# 返回client下的变量print(cf.options('client'))'''['port', 'user', 'password', 'host']'''#判断client下是否存在port变量print(cf.has_option('client','port'))'''True'''#获取client下的port,其他方法:getboolean,getint,getfloatprint(cf.get('client','port'))'''3306'''#===========================增加或删除======================# 删除cf.remove_section('client')# cf.remove_option('client','port')# 添加cf.add_section("mysql")cf.set('mysql','host','127.0.0.1')#保存文件cf.write(open('my.cnf','w'))