Python使用ConfigParser模塊操作配置文件的方法
本文實(shí)例講述了Python使用ConfigParser模塊操作配置文件的方法。分享給大家供大家參考,具體如下:
一、簡(jiǎn)介
用于生成和修改常見配置文檔,當(dāng)前模塊的名稱在 python 3.x 版本中變更為 configparser。
二、配置文件格式
[DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes [bitbucket.org] User = hg [topsecret.server.com] Port = 50022 ForwardX11 = no
三、創(chuàng)建配置文件
import configparser
# 生成一個(gè)處理對(duì)象
config = configparser.ConfigParser()
#默認(rèn)配置
config["DEFAULT"] = {'ServerAliveInterval': '45',
'Compression': 'yes',
'CompressionLevel': '9'}
#生成其他的配置組
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022' # mutates the parser
topsecret['ForwardX11'] = 'no' # same here
config['DEFAULT']['ForwardX11'] = 'yes'
#寫入配置文件
with open('example.ini', 'w') as configfile:
config.write(configfile)
四、讀取配置文件
1、讀取節(jié)點(diǎn)信息
import configparser
config = configparser.ConfigParser()
config.read('example.ini')
# 讀取默認(rèn)配置節(jié)點(diǎn)信息
print(config.defaults())
#讀取其他節(jié)點(diǎn)
print(config.sections())
輸出
OrderedDict([('compression', 'yes'), ('serveraliveinterval', '45'), ('compressionlevel', '9'), ('forwardx11', 'yes')])
['bitbucket.org', 'topsecret.server.com']
2、判讀配置節(jié)點(diǎn)名是否存在
print('ssss' in config)
print('bitbucket.org' in config)
輸出
False
True
3、讀取配置節(jié)點(diǎn)內(nèi)的信息
print(config['bitbucket.org']['user'])
輸出
hg
4.循環(huán)讀取配置節(jié)點(diǎn)全部信息
for key in config['bitbucket.org']: print(key, ':', config['bitbucket.org'][key])
輸出
user : hg
compression : yes
serveraliveinterval : 45
compressionlevel : 9
forwardx11 : yes
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python函數(shù)使用技巧總結(jié)》、《Python面向?qū)ο蟪绦蛟O(shè)計(jì)入門與進(jìn)階教程》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
python3檢查字典傳入函數(shù)鍵是否齊全的實(shí)例
這篇文章主要介紹了python3檢查字典傳入函數(shù)鍵是否齊全的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-06-06
Python檢測(cè)網(wǎng)絡(luò)延遲的代碼
這篇文章主要介紹了Python檢測(cè)網(wǎng)絡(luò)延遲的代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-05-05
用Python和WordCloud繪制詞云的實(shí)現(xiàn)方法(內(nèi)附讓字體清晰的秘笈)
這篇文章主要介紹了用Python和WordCloud繪制詞云的實(shí)現(xiàn)方法(內(nèi)附讓字體清晰的秘笈),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-01-01
如何用OpenCV -python3實(shí)現(xiàn)視頻物體追蹤
OpenCV是一個(gè)基于BSD許可(開源)發(fā)行的跨平臺(tái)計(jì)算機(jī)視覺庫,可以運(yùn)行在Linux、Windows、Android和Mac OS操作系統(tǒng)上。這篇文章主要介紹了如何用OpenCV -python3實(shí)現(xiàn)視頻物體追蹤,需要的朋友可以參考下2019-12-12

