python configparser配置文件解析器

一、Configparser

此模块提供实现基本配置语言的ConfigParser类,该语言提供类似于Microsoft Windows INI文件中的结构。我们经常会在一些软件安装目录下看到.ini后缀的文件,这些文件是软件的配置文件。

1.1.ini配置文件的基本结构

#.ini文件由块组成,每个块包含带值得键
[DEFAULT]      
ServerAliveInterval = 45 
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no

1.2从文件中读取和查看所拥有的数据

import configparser

parser = configparser.ConfigParser()  #获取一个configparser对象
parser.sections() #获取节点列表
parser.read('conf.ini') #读取文件

print(parser['bitbucket.org']['User'])#获取值

for key in parser['bitbucket.org']: print(key)

 1.3增删改查操作

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','k1','11111')
config.set('yuan','k2','22222')

config.write(open('new2.ini', "w"))
原文地址:https://www.cnblogs.com/weihengblog/p/8568021.html