Python 标准库模块 - configparser

前言:如果您使用的是python2开发环境,请下载安装ConfigParser模块;python3已更名为:configparser模块。

一.简介

python中使用configpasser模块读取配置文件,配置文件格式与windows下的.ini配置文件相似,包含一个或多个节(section),每个节可以有多个参数(option---->键=值 或 键:值)。样子如下:

二.常用方法

配置文件常用的“读”操作:

方法 释义
read(filename) 读取配置文件内容
sections() 以列表形式返回所有section
options(section) 以列表形式返回指定section下的所有option
items(section) 得到该section的所有键值对:[(键:值),(键:值),...]
get(section,option) 得到section中option的值,返回为string类型
getint(section,option) 得到section中option的值,返回为int类型
getfloat(section,option) 得到section中option的值,返回为float类型
getboolean(section, option) 得到section中option的值,返回为boolean类型

配置文件常用的“写”操作:

方法 释义
add_section(section) 添加一个新的section
has_section(section) 判断是否有section
set( section, option, value) 对section中的option进行设置
remove_setion(section) 删除一个section
remove_option(section, option) 删除section中的option
write(open("文件名", “w”)) 将内容写入配置文件

三.代码示例

# -*- coding: utf-8 -*-
"""
Created on Tue Dec 25 10:59:30 2018
@author: Gergo
"""
 
import configparser
 
#实例化conf对象
conf = configparser.ConfigParser()
#conf读取配置文件:务必指定编码方式,否则windows下默认以gbk读取utf-8格式的配置文件将会报错
conf.read("config.ini", encoding="utf-8")
 
print('==========================conf.sections()==========================')
sections = conf.sections()
print('sections:', sections)
 
print('\n==========================conf.options(section)==========================')
for section in sections:
    options = conf.options(section)
    print(section, ":" ,options)
 
print('\n==========================conf.items(section)==========================')
for section in sections:
    option_item = conf.items(section)
    print(section, ':', option_item)
 
 
print('\n==========================conf.items优雅之处==========================')
db_dict = dict(conf.items(sections[0]));
print(db_dict)
 
print('\n==========================conf.get(section, option)==========================')
str_val = conf.get("DB", "db_string")
print(str_val)
 
print('\n==========================配置文件写操作==========================')
conf.set("DB", "factory_id", "88888") #更新option的值
conf.set("DB", "factory_id2", "这是一个新的厂商ID") #增加新的option
conf.add_section('NEW_SECTION') #增加新的section
conf.set('NEW_SECTION', 'count', '1')
conf.write(open("config.ini", "w")) #写回配置文件---->这一步很重要

备注:
1.conf.read("文件路径", encoding="utf-8") 需指定读取的编码方式,否则windows下默认以gbk读取,将产生异常;
2.更新配置文件最后必须执行写操作,才可以将修改更新到配置文件。

程序运行结果:

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容