python configparser()配置文件

一、ConfigParser简介

ConfigParser 是用来读取配置文件的包。配置文件的格式如下:中括号“[ ]”内包含的为section。section 下面为类似于key-value 的配置内容。

 1 [DEFAULT]
 2 severallvelimterval = 45
 3 compression = yes
 4 compressionlevel = 9
 5 forwardx11 = yes
 6 
 7 [bitbacket.org]
 8 user = hg
 9 
10 [topsecret.server.com]
11 port  = 50022
12 forwar0x11 = no

  生成配置文件:

import configparser

config = configparser.ConfigParser()

config["DEFAULT"] = {
                   'SeverAllvelImterval': '45',
                   'Compression' : 'yes',
                    'CompressionLevel' : '9',
                     'ForwardX11': 'yes'}
config["bitbacket.org"] = {'User':'hg'}
config["topsecret.server.com"] = {'Port ':'50022',
                                      'Forwar0x11':'no'  }
with open('example.ini','w') as configfile:
     config.write(configfile)

二、ConfigParser 常用方法

1. 获取所有sections。也就是将配置文件中所有“[ ]”读取到列表中:

 

config.read("example.ini")
print(config.sections())

 

将输出:

['bitbacket.org', 'topsecret.server.com']

备注:“DEFAULT”section默认不显示

    2. 获取指定section 的options。即将配置文件某个section 内key 读取到列表中:

config.read("example.ini")
print(config.options("bitbacket.org"))

将输出:

['user', 'severallvelimterval', 'compression', 'compressionlevel', 'forwardx11']

备注:“options”会默认输出default模块的options

3. 获取指定section 的配置信息。

config.read("example.ini")
print(config.items("topsecret.server.com"))

将输出:

[('severallvelimterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('port ', '50022'), ('forwar0x11', 'no'), ('port', '50022')]

4. 按照类型读取指定section 的option 信息。

同样的还有getfloat、getboolean。

print(config.getint("DEFAULT",'SeverAllvelImterval'))

将输出:

  45

5. 设置某个option 的值。(记得最后要写回)

config.set("DEFAULT",'SeverAllvelImterval', '50')
config.write(open('example.ini','w'))

6.添加一个section。(同样要写回)

config.set("DEFAULT",'ant', '50')
config.write(open('example.ini','w'))

7. 移除section 或者option 。(只要进行了修改就要写回的哦)

config.remove_option("DEFAULT",'ant')
config.write(open('example.ini','w'))

config.remove_section("DEFAULT")
config.write(open('example.ini','w'))

 

原文地址:https://www.cnblogs.com/qinyanli/p/8286882.html