python的configparser总结

python操作配置文件读取写入的ConfigParser模块
python version: python3

代码如下

1
2
3
4
5
6
7
8
9
10

[db]
db_port = 3306
db_user = root
db_host = 127.0.0.1
db_pass = sun

[concurrent]
processor = 20
thread = 10

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
# 获取配置文件定义的内容
# -*- coding: utf-8 -*-
# Author: LiChangMing
# Time: 2018/11/16
# Blog: https://MrLichangming.github.io
from configparser import ConfigParser

cf = ConfigParser() #实例化
cf.read("config.ini") #读取配置文件

secs = cf.sections() #获取所有sections,以列表返回 ["db","concurrent"]
print("sections: ", secs, type(secs))

opts = cf.options("db") # 获取sections db下所有options,也就是key
print("options: ", opts, type(opts))

kvs = cf.items("db") # 以列表返回
print("db: ", kvs, type(kvs))
输出:
db: [('db_port', '3306'), ('db_user', 'root'), ('db_host', '127.0.0.1'), ('db_pass', 'sun')] <class ''>


#获取valuecf.getstr返回
db_host = cf.get("db", "db_host")
db_port = cf.get("db", "db_port")
db_user = cf.get("db", "db_user")
db_pass = cf.get("db", "db_pass")
print("db_host: ", db_host, type(db_host))
print("db_port: ", db_port)
print("db_user: ", db_user)
print("db_pass: ", db_pass)

# 获取value,cf.getint 以int类型返回数据
concurrent_processor = cf.getint("concurrent", "processor")
concurrent_thread = cf.getint("concurrent", "thread")
print("conncurrent_processor; ", concurrent_processor, type(concurrent_processor))
print("conncurrent_thread: ", concurrent_thread, type(concurrent_thread))
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
# ConfigParser的修改操作
# cat config2.ini
[hexo]
url = https://localhost:4000
user = guest2
pass = [email protected]123

# modify
# -*- coding: utf-8 -*-
# Author: LiChangMing
# Time: 2018/11/16
# Blog: https://MrLichangming.github.io

from configparser import ConfigParser
import os

cf = ConfigParser()

# modify cf, be sure to read!
cf.read("config2.ini")
cf.set("hexo", "user", "changming")
cf.set("hexo", "pass", "[email protected]@123")

# write file
with open("config2.ini", "w+") as f:
cf.write(f)
f.close()

结果:
[hexo]
url = https://localhost:4000
user = changming
pass = [email protected]@123
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
# -*- coding: utf-8 -*-
# Author: LiChangMing
# Time: 2018/11/16
# Blog: https://MrLichangming.github.io
from configparser import ConfigParser
import os

cf = ConfigParser()

# add section / set option & value
cf.add_section("myblog")
cf.set("myblog", "url", "https://localhost:4000")
cf.set("myblog", "user", "guest")
cf.set("myblog", "pass", "[email protected]")

# write to file
with open("config2.ini", "w+") as f:
cf.write(f)
f.close()

查看内容
[myblog]
url = https://localhost:4000
user = guest
pass = [email protected]123