python——configparser模块

import configparser
#用于生成和修改常见配置文件

config=configparser.ConfigParser()

# 第一部分 创建一个配置文件
# config=configparser.ConfigParser()
#
# config["DEFAULT"]={'ServerAliveInterval':'45',
# 'Compression':'yes',
# 'CompressionLevel':'9'}
#
# config['bitbucket.org']={'User':'hg'}
# config['topsecret.server.com']={}
# topsecret=config['topsecret.server.com']
# topsecret['Hot Port']='50022'
# topsecret['ForwardX11']='no'
# config['DEFAULT']['ForwardX11']='yes'
#
# with open('example.ini','w')as configfile:
# config.write(configfile)

#第二部分 取内部的块
config.read('example.ini')
#先读取 将他们关联起来
print(config.sections())
#['bitbucket.org', 'topsecret.server.com']
#DEFAULT为默认 所以省略
print(config.defaults())
#OrderedDict([('compressionlevel', '9'), ('compression', 'yes'), ('serveraliveinterval', '45'), ('forwardx11', 'yes')])

#取再内部的
print(config['bitbucket.org']['User'])
#hg

print('bitbucket.org' in config)
#True #判断是否在内

for key in config:
print(key)
#DEFAULT
# bitbucket.org
# topsecret.server.com

for key in config['bitbucket.org']:
print(key)
#其结果不仅仅是bitbucket中的,还有默认DEFAULT的
#user
# compressionlevel
# compression
# serveraliveinterval
# forwardx11

# 第三部分删除与更改
config.remove_section('topsecret.server.com')
#删除
config.write(open(('i.cfg'),'w'))
#因为文件一旦写上 就定死了 不会被修改 不能改掉某行 只能重新写一个文件
#若想同文件的话 可与原文件名想同 即覆盖掉原文件

config.set('bitbucket.org','user','lin')
config.write(open('example.ini','w'))
#与上同理 若想更改某处可以用set函数,同时可以覆盖原文件

config.remove_option('bitbucket.org','user')
config.write(open('example.ini','w'))
#与上同理 remove_ption为删除某块选项
原文地址:https://www.cnblogs.com/zzzi/p/11363835.html