本文實例講述了Python使用ConfigParser模塊操作配置文件的方法。分享給大家供大家參考,具體如下:
用于生成和修改常見配置文檔,當前模塊的名稱在 python 3.x 版本中變更為 configparser
。
[DEFAULT]ServerAliveInterval = 45Compression = yesCompressionLevel = 9ForwardX11 = yes[bitbucket.org]User = hg[topsecret.server.com]Port = 50022ForwardX11 = no
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 parsertopsecret['ForwardX11'] = 'no' # same hereconfig['DEFAULT']['ForwardX11'] = 'yes'#寫入配置文件with open('example.ini', 'w') as configfile: config.write(configfile)
import configparserconfig = configparser.ConfigParser()config.read('example.ini')# 讀取默認配置節點信息print(config.defaults())#讀取其他節點print(config.sections())
輸出
OrderedDict([('compression', 'yes'), ('serveraliveinterval', '45'), ('compressionlevel', '9'), ('forwardx11', 'yes')])
['bitbucket.org', 'topsecret.server.com']
print('ssss' in config)print('bitbucket.org' in config)
輸出
False
True
print(config['bitbucket.org']['user'])
輸出
hg
for key in config['bitbucket.org']: print(key, ':', config['bitbucket.org'][key])
輸出
user : hg
compression : yes
serveraliveinterval : 45
compressionlevel : 9
forwardx11 : yes
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python函數使用技巧總結》、《Python面向對象程序設計入門與進階教程》、《Python數據結構與算法教程》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答