configparser模块
作者:互联网
'''文本配置文件:相当于一个字典,[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
'''
标签:bitbucket,##,topsecret,模块,print,org,config,configparser 来源: https://www.cnblogs.com/xuewei95/p/14594793.html