python读写增删修改ini配置⽂件
⼀,百度百科
.ini ⽂件是Initialization File的缩写,即初始化⽂件,是windows的系统所采⽤的存储格式,统管windows的各项配置,⼀般⽤户就⽤windows提供的各项图形化管理界⾯就可实现相同的配置了。但在某些情况,还是要直接编辑ini才⽅便,⼀般只有很熟悉windows才能去直接编辑。
开始时⽤于WIN3X下⾯,WIN95⽤代替,以及后⾯的内容表⽰⼀个节,相当于注册表中的键。
⼆,配置程序
⽰例ini配置⽂件(tting.ini)
1 [txtA]
2 name = comma,end,full,run
3 comma = 1000
4 end = 3
5 full = 2
6 run = 1
7 default_comma = 3
8 default_end = 3
9 default_full = 2
10 default_run = 1
11
12 [txtB]
13 name = comma,end,full,run
14 comma = 1000
15 end = 3
16 full = 2小苏打的用途
17 run = 1
18 default_comma = 3
19 default_end = 3
手机无法连接网络20 default_full = 2月亮变化
螃蟹怎么做好吃又简单方便21 default_run = 1
22公司买卖
茉莉花音乐23 [chine]
24 name = volume,tones,speed,spokesman
25 volume = 5
26 tones = 5
27 speed = 5
28 spokesman = 1
29 default_volume = 5
30 default_tones = 5
31 default_speed = 5
32 default_spokesman = 1
33
34 [english]
35 name = volume,tones,speed,spokesman
36 volume = 5
37 tones = 5
38 speed = 5
39 spokesman = 1
40 default_volume = 5
41 default_tones = 5
42 default_speed = 5
43 default_spokesman = 1
44
45 [help]
46
47 [about]
⽰例ini配置⽂件操作程序1:
使⽤configparr函数,缺点:增删、修改都是重写ini⽂件操作
1import configparr
2import os
3
4
5# *** 初始化配置⽂件路径 *** #
6 curpath = os.path.dirname(alpath(__file__)) # 当前⽂件路径
7 inipath = os.path.join(curpath, "tting.ini") # 配置⽂件路径(组合、相对路径)
8
9# *** 数据读取 *** #
10 conf = configparr.ConfigParr()
治失眠良方
ad(inipath, encoding="utf-8")
12# ctions = ions() # 获取所有的ctions名称
13# options = conf.options(ctions[0]) # 获取ction[0]中所有options的名称
14# items = conf.items(ctions[0]) # 获取ction[0]中所有的键值对
15# value = (ctions[-1],'txt2') # 获取ction[-1]中option的值,返回为string类型16# value1 = int(ctions[0],'comma') # 返回int类型
17# value2 = float(ctions[0],'end') # 返回float类型
18# value3 = boolean(ctions[0],'run') # 返回boolen类型
黄山毛峰功效19
20# *** 删除内容 *** #
21# ve_option(ctions[0], "comma")
22# ve_ction(ctions[1])
23
24# *** 修改内容 *** #
25 conf.t('txtB', "comma", "1000")
26 conf.write(open(inipath, "r+", encoding="utf-8")) # r+模式
27
28
29# print(conf.items(ctions[0]) )
⽰例ini配置⽂件操作程序2:
使⽤configobj 函数
1from configobj import ConfigObj
2# *** 配置⽂件预处理 *** #
3 config = ConfigObj("tting.ini",encoding='UTF8')
4
5# *** 读配置⽂件 *** #
6# print(config['txtB'])
7# print(config['txtB']['name'])
8
9# *** 修改配置⽂件 *** #
10# config['txtB']['comma'] = "Mufasa"
11# config.write()
12
13# *** 添加ction *** #
14# config['txtC'] = {}
15# config['txtC']['index0'] = "wanyu00"
16# config.write()