前言:如果您使用的是python2開發(fā)環(huán)境袍祖,請(qǐng)下載安裝ConfigParser模塊;python3已更名為:configparser模塊谢揪。
一.簡(jiǎn)介
python中使用configpasser模塊讀取配置文件蕉陋,配置文件格式與windows下的.ini配置文件相似,包含一個(gè)或多個(gè)節(jié)(section)拨扶,每個(gè)節(jié)可以有多個(gè)參數(shù)(option---->鍵=值 或 鍵:值)凳鬓。樣子如下:
二.常用方法
配置文件常用的“讀”操作:
方法 | 釋義 |
---|---|
read(filename) | 讀取配置文件內(nèi)容 |
sections() | 以列表形式返回所有section |
options(section) | 以列表形式返回指定section下的所有option |
items(section) | 得到該section的所有鍵值對(duì):[(鍵:值),(鍵:值),...] |
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) | 添加一個(gè)新的section |
has_section(section) | 判斷是否有section |
set( section, option, value) | 對(duì)section中的option進(jìn)行設(shè)置 |
remove_setion(section) | 刪除一個(gè)section |
remove_option(section, option) | 刪除section中的option |
write(open("文件名", “w”)) | 將內(nèi)容寫入配置文件 |
三.代碼示例
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 25 10:59:30 2018
@author: Gergo
"""
import configparser
#實(shí)例化conf對(duì)象
conf = configparser.ConfigParser()
#conf讀取配置文件:務(wù)必指定編碼方式仅孩,否則windows下默認(rèn)以gbk讀取utf-8格式的配置文件將會(huì)報(bào)錯(cuò)
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優(yōu)雅之處==========================')
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", "這是一個(gè)新的廠商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下默認(rèn)以gbk讀取,將產(chǎn)生異常辽慕;
2.更新配置文件最后必須執(zhí)行寫操作京腥,才可以將修改更新到配置文件宣决。
程序運(yùn)行結(jié)果: