python初级之路-configparser模块

python之configparser模块:用于生成和修改常见的配置文件模块。

 1 #!/usr/bin/env python3
 2 # -*- coding: utf-8 -*-
 3 
 4 import configparser
 5 
 6 config = configparser.ConfigParser()    # 定义一个ConfigParser对象
 7 
 8 # 新建一个config配置文件
 9 config["DEFAULT"] = {"ServerAliveInterval": "45",    # 创建DEFAULT节点
10                      "Compression": "yes",
11                      "CompressionLevel": "9"}
12 
13 config["bitbucket.org"] = {}    # 创建bitbucket.org空节点
14 config["bitbucket.org"]["user"] = "lanten"
15 
16 config["topsecret.server.com"] = {}
17 topsecret = config["topsecret.server.com"]
18 topsecret["Host Port"] = "50022"
19 topsecret["ForwardX11"] = "no"
20 
21 config["DEFAULT"]["ForwardX11"] = "yes"
22 
23 with open("example.ini", "w") as configfile:
24     config.write(configfile)    # 将config对象内容写入到configfile文件对象
25 
26 # 读取example.ini文件内容
27 config_read = configparser.ConfigParser()
28 
29 print(config_read.read("example.ini"))    # 读取example.ini文件对象
30 print(config_read.sections())    # 打印example.ini文件中的节点,其中"DEFAULT"节点好像会被认为是根节点,将其纳到对象的属性中
31 print(config_read.defaults())
32 print(config_read["bitbucket.org"]["user"])    # 打印"bitbucket.org"下的user值
33 print(config_read.options("topsecret.server.com"))
34 
35 # 删除example.ini文件中的节点
36 config_remove = configparser.ConfigParser()
37 config_remove.read("example.ini")
38 config_remove.remove_section("bitbucket.org")    # 删除bitbucket.org节点
39 config_remove.write(open("example_remove.ini", "w"))
40 
41 # 新增节点
42 config_add = configparser.ConfigParser()
43 config_add.read("example.ini")
44 if not config_add.has_section("mysqld"):    # 如何"mysqldata"这个节点不存在,则执行下面语句
45     config_add.add_section("mysqld")    # 新增一个"mysqldata"节点
46     config_add["mysqld"]["user"] = "root"
47     config_add["mysqld"]["port"] = "3306"
48     config_add["mysqld"]["datadir"] = "/data/mysqldata"
49 
50 config_add.write(open("my.cnf", "w"))
51 
52 # 修改和移除option
53 config_update = configparser.ConfigParser()
54 config_update.read("example.ini")
55 config_update.set("bitbucket.org", "user", "nidaye")    # 更新bitbucket.org节点中user的值
56 config_update.remove_option("topsecret.server.com", "forwardx11")    # 删除topsecret.server.com节点下forwardx11
57 config_update.write(open("example_update.ini", "w"))

 

输出结果:

 

example.ini文件:

 1 [DEFAULT]
 2 serveraliveinterval = 45
 3 compression = yes
 4 compressionlevel = 9
 5 forwardx11 = yes
 6 
 7 [bitbucket.org]
 8 user = lanten
 9 
10 [topsecret.server.com]
11 host port = 50022
12 forwardx11 = no
posted @ 2020-10-20 20:30  Zombie☠️  阅读(85)  评论(0)    收藏  举报