configparser模块--配置文件

该模块适用于配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。

创建文件

import configparser

config = configparser.ConfigParser()

config["DEFAULT"] = {'ServerAliveInterval': '45',
                      'Compression': 'yes',
                     'CompressionLevel': '9',
                     'ForwardX11':'yes'
                     } #DEFAULT是默认分组,名称必须是DEFAULT

config['bitbucket.org'] = {'User':'hg'} # 每一个config[]是一个组

config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'}

with open('example.ini', 'w') as configfile:

   config.write(configfile)

执行结果-'example.ini'文件内容

[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes

[bitbucket.org]
user = hg

[topsecret.server.com]
host port = 50022
forwardx11 = no
文件内容

查找文件
向字典一样操作

import configparser
config = configparser.ConfigParser() # 需要先创建对象
config.read('example.ini') # 给对象绑定配置文件
print(config.sections()) #  ['bitbucket.org', 'topsecret.server.com'] 返回配置文件中节序列-组名(不包含默认分组)

print('bitbucket.org' in config) # False 判断某个分组是不是在文件里
print(config['bitbucket.org']["user"])  # hg 查看某组的某项
print(config['bitbucket.org']["compressionlevel"])  # 9 默认组的内容被其他组共享
print(config['topsecret.server.com']['ForwardX11'])  # no 当子组中存在与默认组相同的项时,子组查询会使用子组内容
print(config['bitbucket.org']) # <Section: bitbucket.org>
for key in config['bitbucket.org']:     # 注意,有default组会打印default组的键,子组优先
    print(key)
print(config.options('bitbucket.org'))  # 同for循环,找到'bitbucket.org'下所有键,返回一个列表
print(config.items('bitbucket.org'))    #找到'bitbucket.org'下所有键值对,键值对以元组形式返回,存放在列表里
print(config.get('bitbucket.org','compression')) # yes       get方法Section下的key对应的value

增删改操作

import configparser
config = configparser.ConfigParser() # 需要先创建对象
config.read('example.ini') # 给对象绑定配置文件

# config.add_section('yuan') # 增加一个组
# config.remove_section('bitbucket.org') # 删除一个组
# config.remove_option('topsecret.server.com',"forwardx11") # 删除一个组中的一项
# config.set('topsecret.server.com','compression','yes') #给一个组中增加或更改一项,

config.write(open('example.ini', "w")) # 把修改后的内容写会文件才会生效

  

原文地址:https://www.cnblogs.com/wwg945/p/8016733.html