python使用配置文件【configparser模块】

版权声明: https://blog.csdn.net/Geroge_lmx/article/details/85244521

前言:如果您使用的是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.更新配置文件最后必须执行写操作,才可以将修改更新到配置文件。

 程序运行结果:

参考:https://blog.csdn.net/henulwj/article/details/49174355

猜你喜欢

转载自blog.csdn.net/Geroge_lmx/article/details/85244521