亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

 更新時(shí)間:2018年06月29日 10:20:51   作者:Bigberg  
這篇文章主要介紹了Python使用ConfigParser模塊操作配置文件的方法,結(jié)合實(shí)例形式分析了Python基于ConfigParser模塊針對(duì)配置文件的創(chuàng)建、讀取、寫入、判斷等相關(guān)操作技巧,需要的朋友可以參考下

本文實(shí)例講述了Python使用ConfigParser模塊操作配置文件的方法。分享給大家供大家參考,具體如下:

一、簡(jiǎn)介

用于生成和修改常見配置文檔,當(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
# 生成一個(gè)處理對(duì)象
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é)點(diǎn)信息

import configparser
config = configparser.ConfigParser()
config.read('example.ini')
# 讀取默認(rèn)配置節(jié)點(diǎn)信息
print(config.defaults())
#讀取其他節(jié)點(diǎn)
print(config.sections())

輸出

OrderedDict([('compression', 'yes'), ('serveraliveinterval', '45'), ('compressionlevel', '9'), ('forwardx11', 'yes')])
['bitbucket.org', 'topsecret.server.com']

2、判讀配置節(jié)點(diǎn)名是否存在

print('ssss' in config)
print('bitbucket.org' in config)

輸出

False
True

3、讀取配置節(jié)點(diǎn)內(nèi)的信息

print(config['bitbucket.org']['user'])

輸出

hg

4.循環(huán)讀取配置節(jié)點(diǎn)全部信息

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ì)入門與進(jìn)階教程》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論