Python中ConfigParser模块详谈

1. 简介

有些时候在项目中,使用配置文件来配置一些灵活的参数是比较常见的事,因为这会使得代码的维护变得更方便。而ini配置文件是比较常用的一种,今天介绍用ConfigParser模块来解析ini配置文件。

2. ini配置文件格式

# 这是注释
; 这也是注释
[section1]
name = wang
age = 18
heigth = 180

[section2]
name = python
age = 19

3. 读取ini文件

configparser模块为Python自带模块不需要单独安装,但要注意,在Python3中的导入方式与Python2的有点小区别

# python2
import ConfigParser

# python3
import configparser

3.1 初始化对象并读取文件

import configparser
import os
# 创建对象
config = configparser.ConfigParser()
dirPath = os.path.dirname(os.path.realpath(__file__))
inipath = os.path.join(dirPath,'test.ini')
# 读取配置文件,如果配置文件不存在则创建
config.read(inipath,encoding='utf-8')

3.2 获取并打印所有节点名称

secs = config.sections()
print(secs)

输出结果:

['section1', 'section2']

3.3 获取指定节点的所有key

option = config.options('section1')
print(option)

输出结果:

['name', 'age', 'heigth']

3.4 获取指定节点的键值对

item_list = config.items('section2')
print(item_list)

输出结果:

[('name', 'python'), ('age', '19')]

3.5 获取指定节点的指定key的value

val = config.get('section1','age')
print('section1的age值为:',val)

输出结果:

section1的age值为: 18

3.6 将获取到值转换为int\bool\浮点型

Attributes = config.getint('section2','age')
print(type(config.get('section2','age')))
print(type(Attributes))

# Attributes2 = config.getboolean('section2','age')
# Attributes3 = config.getfloat('section2','age')

输出结果:

<class 'str'>
<class 'int'>

3.7 检查section或option是否存在,返回bool值

has_sec = config.has_section('section1')
print(has_sec)

has_opt = config.has_option('section1','name')
print(has_opt)

输出结果:

True
True

3.8 添加一个section和option

if not config.has_section('node1'):
    config.add_section('node1')

# 不需判断key存不存在,如果key不存在则新增,若已存在,则修改value
config.set('section1','weight','100')  

# 将添加的节点node1写入配置文件
config.write(open(inipath,'w'))
print(config.sections())
print(config.options('section1'))

输出结果:

['section1', 'section2', 'node1']
[('name', 'wang'), ('age', '18'), ('heigth', '180'), ('weight', '100')]

3.9 删除section和option

# 删除option
print('删除前的option:',config.items('node1'))
config.remove_option('node1','dd')
# 将删除节点node1后的内容写回配置文件
config.write(open(inipath,'w'))
print('删除后的option:',config.items('node1'))

输出结果:

删除前的option: [('dd', 'ab')]
删除后的option: []
# 删除section
print('删除前的section: ',config.sections())
config.remove_section('node1')
config.write(open(inipath,'w'))
print('删除后的section: ',config.sections())

输出结果:

删除前的section:  ['section1', 'section2', 'node1']
删除后的section:  ['section1', 'section2']

3.10 写入方式

1、write写入有两种方式,一种是删除源文件内容,重新写入:w

config.write(open(inipath,'w'))

另一种是在原文基础上继续写入内容,追加模式写入:a

config.write(open(inipath,'a'))

需要注意的是,config.read(inipath,encoding='utf-8')只是将文件内容读取到内存中,即使经过一系列的增删改操作,只有执行了以上的写入代码后,操作过的内容才会被写回文件,才能生效。

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
社会演员多的头像社会演员多普通用户
上一篇 2023年3月10日
下一篇 2023年3月10日

相关推荐