configparse模块

configparse模块

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

1、创建文件
来看一个好多软件的常见文档格式如下:

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
  
[bitbucket.org]
User = hg
  
[topsecret.server.com]
Port = 50022
ForwardX11 = no

如果想用python生成一个这样的文档怎么做呢?

import configparser

config = configparser.ConfigParser()
config['DEFAULT'] = {'ServerAliveInterval': 45,
                     'Compression': 'yes',
                     'CompressionLevel': 9,
                     'ForwardX11': 'yes'
                     }

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

with open('example.ini', 'w') as f1:
    config.write(f1)

2、查找文件

import configparser
config = configparser.ConfigParser()
config.read('example.ini')   

查找文件内容,基于字典的形式

print(config.sections())        #['bitbucket.org', 'topsecret.server.com']

通过原码可以看到read默认有2个参数:filenames, encoding=None,如果有中文就需要指定编码

config.read('example.ini', encoding='utf8')

判断key值是否在config中

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

打印'DEFAULT'下面的键

print(config['DEFAULT']) #<Section: DEFAULT>
print(config['DEFAULT']['compression'])  #yes

打印Section下的key

for k in config['DEFAULT']:
    print(k)
# serveraliveinterval
# compression
# compressionlevel
# forwardx11

for k in config['bitbucket.org']:
    print(k + ':' + config['bitbucket.org'][k])
# user:hg
# serveraliveinterval:45
# compression:yes
# compressionlevel:9
# forwardx11:yes
# 注意,有default会默认输出default的键

找出所有键值对

print(config.options('bitbucket.org'))
# ['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']
# 同for循环,找到'bitbucket.org'下所有键,有default会默认输出default的键

找到Section下所有键值对

print(config.items('DEFAULT'))
# [('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes')]

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

get方法Section下的key对应的value

print(config.get('DEFAULT', 'compression')) #yes
print(config.get('topsecret.server.com', 'host port')) #50022

3、增删改操作

import configparser

config = configparser.ConfigParser()
config.read('example.ini', encoding='utf8')

增加

config.add_section('test1')
with open('example.ini', 'w') as f:
config.write(f)
# 增加了一个section,名称为[test1]

删除

config.remove_section('bitbucket.org')
with open('example.ini', 'w') as f:
config.write(f)
# 删除了section:[bitbucket.org]

config.remove_option('topsecret.server.com', 'forwardx11')
with open('example.ini', 'w') as f:
config.write(f)
# 删除了topsecret.server.com下的forwardx11键值对

修改

config.set('topsecret.server.com', 'k1', '123')
config.set('topsecret.server.com', 'host port', '50021')

config.set('test1', 'k2', '111')
config.write(open('example.ini', 'w'))
# 设置topsecret.server.com下的k1的值为123, 设置host port的值为50021
# 设置test1下的k2的值为111
# set方法,有则更改,无则添加
# config.write(open(file, 'w'))写法同with open(file, 'w') as config_file:config.write(config_file)

example.ini 结果:
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes

[topsecret.server.com]
host port = 50021
k1 = 123

[test1]
k2 = 111
原文地址:https://www.cnblogs.com/dxnui119/p/13608672.html