19.configparser模块

2019-12-25  本文已影响0人  哈哈大圣

1). 介绍

  1. configparser用于操作Python中的配置文件
  2. 配置文件模块,操作方式类似于字典。
  3. 导入方式
import configparser

2). 操作API

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no
  1. 生成一个配置对象
conf = configparser.ConfigParser()
  1. 解析配置文件
conf.read("conf.ini")
  1. 解析配置文件里面的每一个节点,将节点名放在一个列表里面
    • [DEFAULT]默认配置不会放进去
    • [DEFAULT]的中配置的对象,如果节点没有覆盖,则为默认中的值
conf.sections()
  1. 将默认配置加载进对象
conf.default_section
  1. 获取对应配置节点的对象
a = conf["bitbucket.org"]

# 获取配置中对应的值
b = a["User"]
  1. 获取对应配置节点所有的key
a = conf["bitbucket.org"].keys()
  1. 增强循环方式获取信息
for k, v in conf["bitbucket.org"].items():
    print(k,v)
  1. 判断
if "sss" in conf["bitbucket.org"]:
    print("yes")

3). 综合案例演示

[group1]
k1 = v1
k2:v2   #中间可以为 = 也可以为 :

[group2]
k1 = v1
import configparser
conf = configparser.ConfigParser()
conf.read("conf_test.ini")
conf.options("group1") # 得到keys

# 添加、改写节点
conf.add_section("group3")
conf["group3"]["name"] = "alex li" # 添加值
conf["group3"]["age"] = "2"        # 添加值,必须是字符串
conf.set("group3","k1","111")      # 添加值,对节点进行设置值
conf.write(open("conf_test_new.ini","w"))

# 删除
conf.remove_option("group1","k1") #删除节点中的一个值
conf.remove_section("group3") #将该节点删除
conf.write(open("conf_test_new.ini","w"))
上一篇下一篇

猜你喜欢

热点阅读