国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python使用ConfigParser模塊操作配置文件的方法

2020-02-15 22:05:01
字體:
來源:轉載
供稿:網友

本文實例講述了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)

四、讀取配置文件

1、讀取節點信息

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']

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

更多關于Python相關內容感興趣的讀者可查看本站專題:《Python函數使用技巧總結》、《Python面向對象程序設計入門與進階教程》、《Python數據結構與算法教程》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》

希望本文所述對大家Python程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 德昌县| 靖边县| 抚顺县| 栾川县| 常宁市| 山东省| 邵东县| 白水县| 宜昌市| 原平市| 栖霞市| 宜川县| 林芝县| 师宗县| 麦盖提县| 兰州市| 汉中市| 安图县| 农安县| 兰溪市| 叶城县| 五台县| 富顺县| 平阳县| 汉源县| 边坝县| 交城县| 永川市| 南丹县| 景东| 九江市| 汉源县| 郯城县| 德庆县| 阿拉尔市| 南华县| 徐闻县| 栾城县| 凤城市| 阳江市| 永年县|