對ConfigParser模組的詳細介紹

零下一度
發布: 2017-07-23 13:45:12
原創
1538 人瀏覽過

一、簡介

用於產生和修改常見設定文檔,目前模組的名稱在 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)
登入後複製

  

四、讀取設定檔

1、讀取節點資訊#####
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']
登入後複製
### ### ######2、判讀配置節點名稱是否存在######
print('ssss' in config)
print('bitbucket.org' in config)

#输出
False
True
登入後複製
######  ######3、讀取配置節點內的資訊##### #
print(config['bitbucket.org']['user'])

#输出

hg
登入後複製
######  ######4.循環讀取設定節點全部資訊######
for key in config['bitbucket.org']:
    print(key, ':', config['bitbucket.org'][key])

#输出

user : hg
compression : yes
serveraliveinterval : 45
compressionlevel : 9
forwardx11 : yes
登入後複製
######  ###

以上是對ConfigParser模組的詳細介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門推薦
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!