Python 標(biāo)準(zhǔn)庫模塊 - configparser

前言:如果您使用的是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é)果:

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容