py文件配置

记录使用,方便后期查询。文件配置模板 configparser 使用方法。

增加

1
2
3
4
5
6
7
from configparser import ConfigParser
cfg = ConfigParser()
cfg['TEST_A'] = {'test_a1': 21, 'test_b2': False, 'test_c3': 35.6}
cfg.add_section('TEST_B')
cfg.set('TEST_B', 'ip', '127.0.0.1')
with open('config.ini', 'w') as df:
cfg.write(df)
1
2
3
4
5
6
7
[TEST_A]
test_a1 = 21
test_b2 = False
test_c3 = 35.6

[TEST_B]
ip = 127.0.0.1

删除

1
2
3
4
5
6
from configparser import ConfigParser
cfg = ConfigParser()
cfg.read("config.ini", encoding="utf-8")
cfg.remove_option('TEST_A', 'test_c3')
with open('config.ini', 'w') as df:
cfg.write(df)
1
2
3
4
5
6
[TEST_A]
test_a1 = 21
test_b2 = False

[TEST_B]
ip = 127.0.0.1

修改

1
2
3
4
5
6
from configparser import ConfigParser
cfg = ConfigParser()
cfg.read("config.ini", encoding="utf-8")
cfg.set('TEST_A', 'test_b2', 'old')
with open('config.ini', 'w') as df:
cfg.write(df)
1
2
3
4
5
6
[TEST_A]
test_a1 = 21
test_b2 = old

[TEST_B]
ip = 127.0.0.1

查询

1
2
3
4
5
6
7
8
#文件
[TEST_A]
test_a1 = 21
test_b2 = False
test_c3 = 35.6

[TEST_B]
ip = 127.0.0.1
1
2
3
4
5
6
7
8
9
from configparser import ConfigParser
cfg = ConfigParser()
cfg.read("config.ini", encoding="utf-8")
print(cfg.sections()) #获取所有sections
# 这里如果没有test_a1会抛异常
print(cfg.getint('TEST_A', 'test_a1')) #int类型
print(cfg.getboolean('TEST_A','test_b2')) #Boolean类型
print(cfg.getfloat('TEST_A','test_c3')) #float类型
print(cfg.get('TEST_B','ip')) #str类型
1
2
3
4
5
['TEST_A', 'TEST_B']
21
False
35.6
127.0.0.1