configparser模块

donfag / 2023-08-26 / 原文

configparser是python的内置模块,它提供的ConfigParser类来解析基本的配置文件:
一、读取配置文件:

1 import configparser
2 config = configparser.ConfigParser()
3 config.read("php.ini")
4 print("遍历配置文件:")
5 for section in config.sections():
6     print(section)
7     for key in config[section]:
8         print("\t%s = %s" % (key,config[section][key]))

二、写入配置文件:

 1 import configparser
 2 config = configparser.ConfigParser()
 3 
 4 config['DEFAULT'] = {
 5     "ServerAliveInteraval":"45",
 6     "Compression":"yes",
 7     "CompressionLevel":"9",
 8 }
 9 
10 config["donfag.com.cn"] = {}
11 config["donfag.com.cn"]["User"] = "Lvtong"
12 
13 config["www.dnsme.com"] = {}
14 cndns = config["www.dnsme.com"]
15 cndns["Port"] = "40088"
16 cndns["Forwardx11"] = "no"
17 
18 config["DEFAULT"]["Forwardx11"] = "yes"
19 
20 with open("test.ini","w") as configfile:
21     config.write(configfile)
22 
23 with open("test.ini","r") as f:
24     print(f.read())

返回结果:
[DEFAULT]
serveraliveinteraval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes

[donfag.com.cn]
user = Lvtong

[www.dnsme.com]
port = 40088
forwardx11 = no

注意:
1、section名称是区分大小写的。
2、section下的键值对中的键是不区分大小写的,在写时会统一变成小写保存到文件中。
3、section下的键值对中的值是不区分类型的,都是字符串,具体使用时需要转换成需要的数据类型。
4、section的名称是[DEFAULT]时,其它section的键值会继承[DEFAULT]的键值信息。如本例中的config["donfag.com.cn"]["ServerAliveInteraval"]的值是45