【Python 3.6.1】写配置文件(一)
写配置文件有两种情况,一是覆盖,二是追加,对于程序来说,只需修改一个参数即可。
一、创建配置文件
1 |
[root@dt xxf]# vi wconf.py |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import configparser # 引用configparser模块 #实例化 cf = configparser.ConfigParser() #添加section cf.add_section('odb_201') #添加option及值 cf.set('odb_201','ip','192.168.1.201') cf.set('odb_201','port','1521') #保存至当前目录,文件名为db1.conf cf.write(open("db1.conf","w")) |
说明:如果保存的文件(db1.conf)不存在,那么则创建,如果存在,则覆盖文件中的内容
运行效果如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# 当前目录的内容如下 [root@dt xxf]# ls fun.py hello.py rconf.py wconf.py [root@dt xxf]# # 执行wconf.py程序,生成db1.conf配置文件 [root@dt xxf]# python3 wconf.py [root@dt xxf]# # 查看已生成配置文件 [root@dt xxf]# ls db1.conf fun.py hello.py rconf.py wconf.py [root@dt xxf]# [root@dt xxf]# cat db1.conf [odb_201] ip = 192.168.1.201 port = 1521 [root@dt xxf]# |
二、配置文件追加内容
其实代码上没什么区别,只需要将“w”改为“a”即可,如下:
1 |
[root@dt xxf]# vi wconf.py |
1 2 3 4 5 6 7 8 9 |
import configparser cf = configparser.ConfigParser() cf.add_section('odb_208') cf.set('odb_208','ip','192.168.1.208') cf.set('odb_208','port','1521') cf.write(open("db1.conf","a")) |
运行效果如下(可以看到,section odb_208已追加):
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# 执行程序 [root@dt xxf]# python3 wconf.py # 查看结果 [root@dt xxf]# cat db1.conf [odb_201] ip = 192.168.1.201 port = 1521 [odb_208] ip = 192.168.1.208 port = 1521 [root@dt xxf]# |
三、删除section
1 |
[root@dt xxf]# vi wconf.py |
编辑wconf.py,效果,判断
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import configparser # 定义两个变量 v_sec_name = "odb_201" v_fname = "db.conf" # 初始化实例,读文件 cf = configparser.ConfigParser() cf.read(v_fname) # 如果存在指定section,那么将其删除,否则,插入指定section if cf.has_section(v_sec_name ) == True: # 删除option,以下是删除option的方法,当然,如果删除了section的话,那么option是自动删除的 #cf.remove_option(v_sec_name,'ip') #cf.remove_option(v_sec_name,'port') cf.remove_section(v_sec_name) cf.write(open(v_fname,"w")) else: # clear() 非常重要,因为在程序开始的时候,我们使用了read,此时,db.conf中的所有内容都读到了缓存,如果不clear,那么程序不但会add指定的section,也会同时将缓存的内存都再保存一次。读者可将clear注释后测试一下 cf.clear() cf.add_section(v_sec_name) cf.set(v_sec_name,'ip','192.168.1.201') cf.set(v_sec_name,'port','1521') cf.write(open(v_fname,"a")) |
验证:
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 |
# 查看配置文件db.conf,此时文件中有三个section [root@dt xxf]# cat db.conf [odb_8] ip = 192.168.1.8 port = 1521 [odb_9] ip = 129 port = 1521 [odb_201] ip = 192.168.1.201 port = 1521 [root@dt xxf]# # 执行程序 [root@dt xxf]# python3 wconf.py # 再次查看,结果是odb_201已经被删除 [root@dt xxf]# cat db.conf [odb_8] ip = 192.168.1.8 port = 1521 [odb_9] ip = 129 port = 1521 [root@dt xxf]# # 再次执行程序 [root@dt xxf]# python3 wconf.py # odb_201已经添加上了 [root@dt xxf]# cat db.conf [odb_8] ip = 192.168.1.8 port = 1521 [odb_9] ip = 129 port = 1521 [odb_201] ip = 192.168.1.201 port = 1521 [root@dt xxf]# |
四、小结
本篇文章介绍了添加、删除配置文件中的section及option,同时也用到了clear()方法。
顺带也用到了if语句。