怎么在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
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)import configparser
config = 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中使用ConfigParser模塊對配置文件進行操作問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。