码迷,mamicode.com
首页 > 编程语言 > 详细

python模块-configparser模块

时间:2018-11-22 02:38:57      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:port   with   efault   host   sam   写入   col   mutate   bsp   

生成配置文件的模块

DEFAULT块,在以块为单位取块的值时,都会出现

import configparser
config = configparser.ConfigParser()  #相当于生成了一个空字典config{}

config["DEFAULT"] = {‘ServerAliveInterval‘: ‘45‘,
                     ‘Compression‘: ‘yes‘,
                     ‘CompressionLevel‘: ‘9‘}  #使用字典的方式给config赋值

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

with open(‘example.ini‘, ‘w‘) as f:
    config.write(f)  #将删除内容写入文件

#生成文件的内容如下
#[DEFAULT]
#serveraliveinterval = 45
#compression = yes
#compressionlevel = 9

#[bitbucket.org]
#user = hg

#[topsecret.server.com]
#host port = 50022
#forwardx11 = no

 

通过config.sections()可获取除了DEFAULT之外的块名

config.read(‘example.ini‘)  #读取文件
print(config.sections())  #config.sections()返回一个列表[‘bitbucket.org‘, ‘topsecret.server.com‘],包含除了DEFAULT之外的块名,需要事先读取文件
print(config[‘bitbucket.org‘][‘user‘])  #使用字典的方式取值
print(config[‘DEFAULT‘][‘compression‘])

 

当遍历除了DEFAULT之外的某一个块时,DEFAULT的内容也会被显示

for i in config[‘bitbucket.org‘]:
    print(i)
#输出结果如下
# user
# serveraliveinterval
# compression
# compressionlevel

 

通过config.options()和config.items()获取块的键和键值对,可看出DEFAULT块全全部显示了

print(config.options(‘bitbucket.org‘))
print(config.items(‘bitbucket.org‘))
#输出内容如下
# [‘user‘, ‘serveraliveinterval‘, ‘compression‘, ‘compressionlevel‘]
# [(‘serveraliveinterval‘, ‘45‘), (‘compression‘, ‘yes‘), (‘compressionlevel‘, ‘9‘), (‘user‘, ‘hg‘)]

 

python模块-configparser模块

标签:port   with   efault   host   sam   写入   col   mutate   bsp   

原文地址:https://www.cnblogs.com/Forever77/p/9998711.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!