Python使用ConfigParser模塊操作配置文件的方法
本文實例講述了Python使用ConfigParser模塊操作配置文件的方法。分享給大家供大家參考,具體如下:
一、簡介
用于生成和修改常見配置文檔,當前模塊的名稱在 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
# 生成一個處理對象
config = configparser.ConfigParser()
#默認配置
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é)點信息
import configparser
config = configparser.ConfigParser()
config.read('example.ini')
# 讀取默認配置節(jié)點信息
print(config.defaults())
#讀取其他節(jié)點
print(config.sections())
輸出
OrderedDict([('compression', 'yes'), ('serveraliveinterval', '45'), ('compressionlevel', '9'), ('forwardx11', 'yes')])
['bitbucket.org', 'topsecret.server.com']
2、判讀配置節(jié)點名是否存在
print('ssss' in config)
print('bitbucket.org' in config)
輸出
False
True
3、讀取配置節(jié)點內的信息
print(config['bitbucket.org']['user'])
輸出
hg
4.循環(huán)讀取配置節(jié)點全部信息
for key in config['bitbucket.org']: print(key, ':', config['bitbucket.org'][key])
輸出
user : hg
compression : yes
serveraliveinterval : 45
compressionlevel : 9
forwardx11 : yes
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python函數(shù)使用技巧總結》、《Python面向對象程序設計入門與進階教程》、《Python數(shù)據(jù)結構與算法教程》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
相關文章
用Python和WordCloud繪制詞云的實現(xiàn)方法(內附讓字體清晰的秘笈)
這篇文章主要介紹了用Python和WordCloud繪制詞云的實現(xiàn)方法(內附讓字體清晰的秘笈),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-01-01
如何用OpenCV -python3實現(xiàn)視頻物體追蹤
OpenCV是一個基于BSD許可(開源)發(fā)行的跨平臺計算機視覺庫,可以運行在Linux、Windows、Android和Mac OS操作系統(tǒng)上。這篇文章主要介紹了如何用OpenCV -python3實現(xiàn)視頻物體追蹤,需要的朋友可以參考下2019-12-12

