Python3 read and write configuration files-detailed explanation of the configparser module

1. Introduction to configparser

configparser is a module used to parse configuration files in the Pyhton standard library, and its built-in methods are very similar to dictionaries. Python2.x is called ConfigParser, 3.x has been renamed configParser, and some new features have been added.

The format of the configuration file is as follows:

[logoninfo]
addr=zhangsan
passwd=lisi
popserver=emain

[logging]
level=2
path= "/root"
server="login"

[mysq]
host=127.0.0.1
port=3306
user=root
password=123456

"[ ]" contains section, below section is the configuration content similar to key-value;
configparser supports'='':' two kinds of separation by default, the following is also legal

[mysq]
host:127.0.0.1
port:3306
user:root
password:123456

2. Read the content of the file

  • Initialize the instance: To use configparser, you first need to initialize the instance and read the configuration file
  • Get all sections
  • Get the keys of the specified section
  • Get the value of the specified key
  • Get the keys & values ​​of the specified section
  • Check if the section exists
  • Check whether the key exists in the specified section
  • Check the value of the specified key in the specified section

The following functions are directly implemented in the code one by one

#coding=utf-8
import configparser

# 初始化实例
conf = configparser.ConfigParser()
print(type(conf))           #conf是类
conf.read('config.ini')

# 获取所有 sections
sections = conf.sections()  #获取配置文件中所有sections,sections是列表
print(sections)

# 获取指定 section 的 keys
option = conf.options(conf.sections()[0]) #获取某个section下的所有选项或value,等价于 option = conf.options('logoninfo')
print(option)

# 获取指定 key 的 value
value = conf.get('logoninfo', 'addr')   #根据section和value获取key值,等价于value = conf.get(conf.sections()[0], conf.options(conf.sections()[0])[0])
print(value)

# 获取指定 section 的 keys & values
item = conf.items('logoninfo')
print(item)

# 检查 section 是否存在
print("xxxxxxxxxxxxxx")
print('logging' in conf) # 或者 print('logging' in conf.sections())

# 检查指定 section 中 key 是否存在
print("addr" in conf["logoninfo"])

# 检查指定 section 指定 key 的 value
print("zhangsan" in conf["logoninfo"]["addr"]) #等于 "zhangsan" == conf["logoninfo"]["addr"]

3. Generate configuration files

import configparser                     # 引入模块

config = configparser.ConfigParser()    #实例化一个对象

config["logoninfo"] = {
    
                     # 类似于操作字典的形式
    'addr': "zhangsan",
    'passwd': "lisi",
    'popserver': "emain"
}

config['logging'] = {
    
    
    "level": '2',
    "path": "/root",
    "server": "login",
    'User': 'Atlan'
}

config['mysq'] = {
    
    
    'host': '127.0.0.1',
    'port': '3306',
    'user': 'root',
    'password': '123456'
}

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

4. Modify the configuration file

import configparser

config = configparser.ConfigParser()			# 实例化一个对象

config.read('config.ini')                       # 读文件

config.add_section('yuan')                      # 添加 section

config.remove_section('mysq.org')               # 删除 section
config.remove_option('logoninfo', "popserver")  # 删除一个配置项

config.set('logging', 'level', '3')				# 修改执行 section 指定 key 的 value
config.set('yuan', 'k2', '22222')				# 添加一个配置项
with open('config.ini', 'w') as f:
    config.write(f)

Guess you like

Origin blog.csdn.net/happyjacob/article/details/109346625