• Python configparser模块


    一、用于生成和修改常见配置文档,当前模块的名称在python3.x版本中变更为configparser.

    二、配置和生成文件

      1、代码

     1 import configparser
     2 
     3 config = configparser.ConfigParser()
     4 config["DEFAULT"] = {
     5                         "wohaoshuai1":'wohaoshuai1',
     6                         "wohaoshuai2":"wohaoshuai2"
     7                         }
     8 config["wohsoshuai_1"] = {}
     9 config["wohsoshuai_1"]["user"] = "wohaoshuai"
    10 
    11 config["wohaoshuai_2"] = {}
    12 aaa = config["wohaoshuai_2"]
    13 aaa["Host port"] = "50022"
    14 
    15 config["DEFAULT"]["name"] = "wohaoshuai3"
    16 
    17 with open("example.ini","w") as configfile:
    18         config.write(configfile)
      2、生成的example.ini如下
    [DEFAULT]#此默认值为全局变量,下面的key在所有节点中都可以引用,如:config["wohaoshuai_1"]["name"],在下面读环境会介绍
    wohaoshuai1 = wohaoshuai1
    wohaoshuai2 = wohaoshuai2
    name = wohaoshuai3
    
    [wohsoshuai_1]
    user = wohaoshuai
    
    [wohaoshuai_2]
    host port = 50022

    三、读文件

     1 import configparser
     2 
     3 config = configparser.ConfigParser()
     4 config.sections()#读出来下面有几个节点,当前为0个
     5 config.read("example.ini")
     6 print(config.sections())#列出下面有几个节点,不会包含default
     7 
     8 print(config.defaults())#获取defaults的key和value
     9 
    10 print("wohaoshuai_1" in config)#判断对象中是否有"wohaoshuai_1"节点
    11 
    12 print(config["wohaoshuai_1"]["name"])
    13 for key in config["wohaoshuai_1"]:
    14     print(key)

    四、增删改查文件

     1 import configparser
     2 
     3 config = configparser.ConfigParser()
     4 config.sections()#读出来下面有几个节点,当前为0个
     5 config.read("example.ini")
     6 
     7 sec = config.remove_section("wohaoshuai_1") #删除节点
     8 config.write(open("wohaoshuai.ini","w"))    #写入到新文件中
     9 
    10 #增加节点和属性
    11 print(config.has_section("wohaoshuai_2"))
    12 config.add_section("wohaoshuai_3")
    13 config["wohaoshuai_3"]["age"] = "21"
    14 config.write(open("wohaoshuai3.ini","w"))
    15 
    16 #修改节点属性
    17 config.set("wohaoshuai_3","age","22")
    18 config.write(open("wohaoshuai4.ini","w"))
  • 相关阅读:
    Lc5413_重新排列句子中的单词
    Lc5412._在既定时间做作业的学生人数
    Lc520_检测大写字母
    threadPoolExecutor的参数和拒绝策略
    coutdownlatch的使用
    volatile的个人理解
    Lc292_Nim 游戏
    Lc136_只出现一次的数字
    lc88_合并两个有序数组
    jdk源码_String(1)
  • 原文地址:https://www.cnblogs.com/Presley-lpc/p/9533302.html
Copyright © 2020-2023  润新知