Python中ConfigParser模塊示例詳解
1. 簡介
有些時候在項目中,使用配置文件來配置一些靈活的參數是比較常見的事,因為這會使得代碼的維護變得更方便。而ini配置文件是比較常用的一種,今天介紹用ConfigParser模塊來解析ini配置文件。
2. ini配置文件格式
# 這是注釋 ; 這也是注釋 [section1] name = wang age = 18 heigth = 180 [section2] name = python age = 19
3. 讀取ini文件
configparser模塊為Python自帶模塊不需要單獨安裝,但要注意,在Python3中的導入方式與Python2的有點小區(qū)別
# python2 import ConfigParser # python3 import configparser
3.1 初始化對象并讀取文件
import configparser import os # 創(chuàng)建對象 config = configparser.ConfigParser() dirPath = os.path.dirname(os.path.realpath(__file__)) inipath = os.path.join(dirPath,'test.ini') # 讀取配置文件,如果配置文件不存在則創(chuàng)建 config.read(inipath,encoding='utf-8')
3.2 獲取并打印所有節(jié)點名稱
secs = config.sections() print(secs)
輸出結果:
['section1', 'section2']
3.3 獲取指定節(jié)點的所有key
option = config.options('section1')
print(option)輸出結果:
['name', 'age', 'heigth']
3.4 獲取指定節(jié)點的鍵值對
item_list = config.items('section2')
print(item_list)輸出結果:
[('name', 'python'), ('age', '19')]
3.5 獲取指定節(jié)點的指定key的value
val = config.get('section1','age')
print('section1的age值為:',val)輸出結果:
section1的age值為: 18
3.6 將獲取到值轉換為int\bool\浮點型
Attributes = config.getint('section2','age')
print(type(config.get('section2','age')))
print(type(Attributes))
# Attributes2 = config.getboolean('section2','age')
# Attributes3 = config.getfloat('section2','age')輸出結果:
<class 'str'>
<class 'int'>
3.7 檢查section或option是否存在,返回bool值
has_sec = config.has_section('section1')
print(has_sec)
has_opt = config.has_option('section1','name')
print(has_opt)輸出結果:
TrueTrue
3.8 添加一個section和option
if not config.has_section('node1'):
config.add_section('node1')
# 不需判斷key存不存在,如果key不存在則新增,若已存在,則修改value
config.set('section1','weight','100')
# 將添加的節(jié)點node1寫入配置文件
config.write(open(inipath,'w'))
print(config.sections())
print(config.options('section1'))輸出結果:
['section1', 'section2', 'node1']
[('name', 'wang'), ('age', '18'), ('heigth', '180'), ('weight', '100')]
3.9 刪除section和option
# 刪除option
print('刪除前的option:',config.items('node1'))
config.remove_option('node1','dd')
# 將刪除節(jié)點node1后的內容寫回配置文件
config.write(open(inipath,'w'))
print('刪除后的option:',config.items('node1'))輸出結果:
刪除前的option: [('dd', 'ab')]
刪除后的option: []
# 刪除section
print('刪除前的section: ',config.sections())
config.remove_section('node1')
config.write(open(inipath,'w'))
print('刪除后的section: ',config.sections())輸出結果:
刪除前的section: ['section1', 'section2', 'node1']
刪除后的section: ['section1', 'section2']
3.10 寫入方式
1、write寫入有兩種方式,一種是刪除源文件內容,重新寫入:w
config.write(open(inipath,'w'))
另一種是在原文基礎上繼續(xù)寫入內容,追加模式寫入:a
config.write(open(inipath,'a'))
需要注意的是,config.read(inipath,encoding='utf-8')只是將文件內容讀取到內存中,即使經過一系列的增刪改操作,只有執(zhí)行了以上的寫入代碼后,操作過的內容才會被寫回文件,才能生效。
到此這篇關于Python中ConfigParser模塊詳談的文章就介紹到這了,更多相關Python中ConfigParser模塊內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python請求庫發(fā)送HTTP POST請求的示例代碼
這段代碼使用了Python的requests庫來發(fā)送HTTP POST請求,向本地服務器的API發(fā)送數據,并處理響應,一步步解釋這個代碼2024-08-08

