Python——configparser模块

configparser 模块

configparser 用于解析配置文件的模块,我们会在配置文件中,放入一些配置程序的信息,通常而言,这些配置信息是我们不需要经常去改动的信息,例如数据文件的路径 DB_PATH

在配置文件中,只有两种内容:

  • section分区
  • option 选项

通常我们用get功能,从配置文件中获取一个配置选项。

Case
1
2
3
4
5
6
7
8
9
10
# file: test.cfg
# 路径相关的配置
[path]
db_path = /a/b/c/test.txt
# 用户相关的配置
[user]
name = oOC
# 服务相关的配置
[server]
url = 192.168.0.0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# file: configparser模块.py
import configparser

config = configparser.ConfigParser()
config.read('test.cfg',encoding='utf-8') # 读取一个配置文件
# 获取需要的信息
# 获取所有的分区
print(config.sections())
# ['path', 'user', 'server']

# 获取所有选项
print(config.options('user'))
# ['name']

# 获取路径
print(config.get('path','db_path'))
# /a/b/c/test.txt

# 获取用户名
print(config.get('user','name'))
# oOC

# get返回的都是字符串类型 如果需要转换类型
# 直接使用get+对应的类型(bool int float)
getfloat()
getint()
getbool()

# 是否由某个选项
config.has_option()
# 是否由某个分区
config.has_section()
# 返回布尔值

# 添加
config.add_section("server")
config.set("server","url","192.168.1.2")
# 删除
config.remove_section
config.remove_option("user")
# 修改
config.set("server","url","192.168.1.2")

# 写回文件中
with open("test.cfg", "wt", encoding="utf-8") as f:
config.write(f)