Python模块——configparser

configparser模块

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

创建文件

import configparser

config = configparser.ConfigParser()

config["DEFAULT"] = {'ServerAliveInterval': '45',
                      'Compression': 'yes',
                     'ForwardX11':'yes'
                     }

config['bitbucket.org'] = {'User':'hg'}

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

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

   config.write(configfile)

文件内容

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

[bitbucket.org]
user = hg

[topsecret.server.com]
host port = 9999
forwardx11 = no

查找文件内容

方法描述
defaults() 返回包含实例范围默认值的字典。
sections() 返回可用的section的列表;默认section不包括在列表中
has_section(section) 指示指定的section是否出现在配置中。默认的section未被确认
options(section) 返回指定section中可用的选项列表。
has_option(section, option) 如果给定的section存在,并且包含给定的选项,则返回True;否则返回False
get(section, option) 为指定的section获取一个选项值。
getint(section, option) 它将指定section中的选项强制转换为整数
getfloat(section, option) 它将指定section中的选项强制转换为浮点型
getboolean(section, option) 强制转换为布尔型,”1”, “yes”, “true”, and “on”, 转换为True,”0”, “no”, “false”, and “off”, 转换为Falseo 其他返回ValueError.
items(section) 返回给定section中每个选项的(name,value)对的列表。
import configparser

config = configparser.ConfigParser()

print(config.sections()) # []
# ---------------------------查找文件内容,基于字典的形式
config.read('example1.ini')  # ['bitbucket.org', 'topsecret.server.com']

print(config.sections())
print('bytebong.com' in config) # False
print('bitbucket.org' in config) # True


print(config['bitbucket.org']["user"])  # hg

print(config['DEFAULT']['Compression']) #yes

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'下所有键
# ['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']

print(config.items('bitbucket.org'))    #找到'bitbucket.org'下所有键值对
# [('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]

print(config.get('bitbucket.org','compression')) # yes       get方法Section下的key对应的value
print(config.get('topsecret.server.com','host port')) # 9999

for k, v in config.items('bitbucket.org'):
    print(k, v)
"""
serveraliveinterval 45
compression yes
forwardx11 yes
user hg
"""

修改和删除文件内容

增加配置文件中的值

方法描述
add_section(section) 向实例添加一个section

删除配置文件中的值

方法描述
remove_option(section, option) 从指定的部分中删除指定的选项。如果该部分不存在,请提出NoSectionError。如果存在的选项被删除,返回True;否则返回False。
remove_section(section) 从配置中删除指定的section。如果这个部分确实存在,返回True。否则返回假

修改配置文件中的值

方法描述
set(section, option, value) 如果给定的部分存在,将给定的选项设置为指定的值
import configparser

config = configparser.ConfigParser()

config.read('example.ini')

config.add_section('db')  # 增加


config.remove_section('bitbucket.org')  # 删除
config.remove_option('topsecret.server.com',"forwardx11")  # 删除


config.set('topsecret.server.com','k1','11111')  # 修改
config.set('db','k2','22222') # 修改

config.write(open('new2.ini', "w"))

 

posted @ 2018-04-16 10:22  一只小小的寄居蟹  阅读(306)  评论(0编辑  收藏  举报