溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python內(nèi)置模塊ConfigParser實現(xiàn)配置讀寫功能的方法

發(fā)布時間:2020-10-02 10:36:57 來源:腳本之家 閱讀:194 作者:蒼松 欄目:開發(fā)技術(shù)

本文實例講述了Python內(nèi)置模塊ConfigParser實現(xiàn)配置讀寫功能的方法。分享給大家供大家參考,具體如下:

用于對特定的配置進行操作,當(dāng)前模塊的名稱在 python 3.x 版本中變更為 configparser。

#配置文件test.cfg
[section1]
k1 = v1
k2 :v2
k3 = 1
[section2]
k1 = v1

#coding:utf-8
import ConfigParser
config = ConfigParser.ConfigParser()
config.read('test.cfg')
# ########## 讀 ##########
#獲取所有sections.
secs = config.sections()
print secs #['section1', 'section2']
#獲取制定section的鍵key
options = config.options('section1')
print options  #['k1', 'k2', 'k3']
#獲取指定section的鍵值對key-value
item_list = config.items('section1')
print item_list #[('k1', 'v1'), ('k2', 'v2'), ('k3', '1')]
#獲取指定key的value
# 獲取字符串類型的value
val1 = config.get('section1','k1')
# 獲取整型的value
val2 = config.getint('section1','k3')
# ########## 增改刪 ##########
# 增加section
if not config.has_section('section3'):
  config.add_section('section3')
  config.write(open('test.cfg', "w"))
#設(shè)置option
if not config.has_section('section3'):
  config.set('section3','k1',11111)
  config.write(open('test.cfg', "w"))
# 移除option
ret = config.remove_option('section3','k1')
print ret  #True or False
config.write(open('test.cfg', "w"))
# 移除section
ret = config.remove_section('section3')
print ret  #True or False
config.write(open('test.cfg', "w"))

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》

希望本文所述對大家Python程序設(shè)計有所幫助。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI