Python使用ConfigParser模塊操作配置文件的方法
本文實例講述了Python使用ConfigParser模塊操作配置文件的方法。分享給大家供大家參考,具體如下:
一、簡介
用于生成和修改常見配置文檔,當(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
# 生成一個處理對象
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é)點信息
import configparser
config = configparser.ConfigParser()
config.read('example.ini')
# 讀取默認(rèn)配置節(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é)點內(nèi)的信息
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
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python函數(shù)使用技巧總結(jié)》、《Python面向?qū)ο蟪绦蛟O(shè)計入門與進(jìn)階教程》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
Python序列對象與String類型內(nèi)置方法詳解
這篇文章主要介紹了Python序列對象與String類型內(nèi)置方法,結(jié)合實例形式分析了Python序列對象與String類型各種常見內(nèi)置方法相關(guān)使用技巧及操作注意事項,需要的朋友可以參考下2019-10-10
PyQt5實現(xiàn)數(shù)據(jù)的增刪改查功能詳解
這篇文章主要為大家介紹了如何使用Python中的PyQt5模塊來實現(xiàn)數(shù)據(jù)的增、刪、改、查功能,文中示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2022-03-03
jupyter lab的目錄調(diào)整及設(shè)置默認(rèn)瀏覽器為chrome的方法
這篇文章主要介紹了jupyter lab的目錄調(diào)整及設(shè)置默認(rèn)瀏覽器為chrome的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04
Python?對象拷貝及深淺拷貝區(qū)別的詳細(xì)教程示例
這篇文章主要介紹了Python?對象拷貝及深淺拷貝區(qū)別的詳細(xì)教程示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03
對python中數(shù)組的del,remove,pop區(qū)別詳解
今天小編就為大家分享一篇對python中數(shù)組的del,remove,pop區(qū)別詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-11-11

