configparser模块

configparser模块:

  • 此模块提供了它实现一种基本配置语言 ConfigParser 类,这种语言所提供的结构与 Microsoft Windows INI 文件的类似。 你可以使用这种语言来编写能够由最终用户来自定义的 Python 程序。
  • 在Python3中configparser模块是纯小写,Python2中采用驼峰体 ConfigParser

例如配置文件如下

# 注释1
# 注释2

[section1]
k1 = v1
k2:v2
user = libai
age = 18
is_admin = true
salary = 31

[section2]
k1 = v1

[第三部分]
...
[第四部分]
...

读取

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

# 获取所有的标题sections
print(config.sections())
# ['section1', 'section2']

# 获取某一section下的所有配置项options的key
print(config.options('section1'))
# ['k1', 'k2', 'user', 'libai', 'is_admin', 'salary']

# 获取某一section下的所有配置项options的键和值组成列表,放在一个大列表内
print(config.items('section1')
# [('k1', 'v1'), ('k2', 'v2'), ('user', 'libai'), ('age', '18'), ('is_admin', 'true'), ('salary', '31')]
      
# 获取某一section下某一option的值
print(config.get('section1','k2'))
# v2  结果为str类型
      
# 获取某一section下某一option的值并转为整型
print(config.getint('section1','age'))
# 18 <class 'int'>
      
# 获取某一section下某一option的值并转为浮点型
print(config.getfloat('section1','age'))
# 18.0

# 获取某一section下某一option的值并转为布尔值
print(config.getboolean('section1','is_admin'))
# True

改写

import configparser

config=configparser.ConfigParser()
config.read('a.cfg',encoding='utf-8')


#删除整个标题section2
config.remove_section('section2')

#删除标题section1下的某个k1和k2
config.remove_option('section1','k1')
config.remove_option('section1','k2')

#判断是否存在某个标题
print(config.has_section('section1'))

#判断标题section1下是否有user
print(config.has_option('section1',''))


#添加一个标题
config.add_section('libai')

#在标题egon下添加name=libai,age=18的配置
config.set('libai','name','libai')
config.set('libai','age',18) #报错,必须是字符串


#最后将修改的内容写入文件,完成最终的修改
config.write(open('a.cfg','w'))

基于上述方法添加一个ini文档。

import configparser
  
config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '45',
                      'Compression': 'yes',
                     'CompressionLevel': '9'}
  
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022'     # mutates the parser
topsecret['ForwardX11'] = 'no'  # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
   config.write(configfile)

原文地址:https://www.cnblogs.com/ChiRou/p/14277950.html