码迷,mamicode.com
首页 > 其他好文 > 详细

configparser模块

时间:2021-03-31 11:46:17      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:key值   结果   删除   conf   item   host   set   文本   --   

‘‘‘文本配置文件:相当于一个字典,[DEFAULT][bitbucket.org][topsecret.server.com]都是key值,所对应的数据是字典格式‘‘‘

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‘
# topsecret[‘ForwardX11‘] = ‘no‘
#
# config[‘DEFAULT‘][‘ForwardX11‘] = ‘yes‘
#
# with open(‘example.ini‘, ‘w‘) as f:
# config.write(f) # 和之前的文件写入操作有点不一样,这里的f是作为参数


# -------------------------------查-------------------------------
# print(config.sections()) # []没有对任何一个文件进行读取,所以取到的块名为空
# config.read(‘example.ini‘)
# print(config.sections()) # [‘bitbucket.org‘, ‘topsecret.server.com‘]默认块名‘[DEFAULT]‘没有进行读取,所以只有两个

# print(‘bytebong.com‘ in config) # False
# print(‘DEFAULT‘ in config) # True
# print(‘bitbucket.org‘ in config) # True

# print(config[‘bitbucket.org‘][‘User‘]) # Hg

# for key in config[‘bitbucket.org‘]:
# print(key) # user、serveraliveinterval、compression、compressionlevel、forwardx11----->DEFAULT是有特殊意义的,不同于其它键,当遍历其它键的时候,它都会跟着出现;如果不想要,就别以DEFAULT命名
# for key in config[‘topsecret.server.com‘]:
# print(key) # host port、forwardx11、serveraliveinterval、compression、compressionlevel----->forwawrdx11键同名了,所以这里只打印一个

# print(config.options(‘bitbucket.org‘)) # [‘user‘, ‘serveraliveinterval‘, ‘compression‘, ‘compressionlevel‘, ‘forwardx11‘]和上面遍历键一样的结果,只不过放在了列表里

# print(config.items(‘bitbucket.org‘)) # [(‘serveraliveinterval‘, ‘45‘), (‘compression‘, ‘yes‘), (‘compressionlevel‘, ‘9‘), (‘forwardx11‘, ‘yes‘), (‘user‘, ‘Hg‘)]

# print(config.get(‘bitbucket.org‘, ‘compressionlevel‘)) # ‘9‘----->就是要传两个参数,少一个就会报错


# -------------------------------删,改,增config.write(open(‘i.cfg‘, ‘w‘))-------------------------------
# config.read(‘example.ini‘)
#
# config.add_section(‘yuan‘) # 增加一个块
#
# config.set(‘yuan‘, ‘k1‘, ‘v1‘) # 在指定的块下面添加数据,第二个值为key,第三个值为value
#
# config.remove_section(‘topsecret.server.com‘) # ‘topsecret.server.com‘块被删除
#
# config.remove_option(‘bitbucket.org‘, ‘user‘) # 把‘bitbucket.org‘块下面的‘user‘键值对删除
#
# config.set(‘yuan‘, ‘k1‘, ‘v2‘) # 修改某一个块下面键值对的值数据
#
# config.write((open(‘i.cfg‘, ‘w‘))) # 这种写法可以不用close


# example.ini文件里的数据
‘‘‘
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes

[bitbucket.org]
user = Hg

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

 

configparser模块

标签:key值   结果   删除   conf   item   host   set   文本   --   

原文地址:https://www.cnblogs.com/xuewei95/p/14594793.html

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