python configparser库简介

系统 1518 0

随着脚本复杂程度增加, 配置文件成了必不可少。之前一直使用json文件,当作配置文件。比较之下, configparser 库更加适合。
下述文件为一个简单的 configparser 库的配置文件
config.ini

            
              [testdb]
db_port = 3306
db_host = 127.0.0.1
db_user = root
db_passwd = 123456

# remark
[zhfx]
target = "zy-zhfx"
targets = ["zy-zhfx"]
num = 3

            
          

上述方括号内的 [] 称之为 section ,等号 = 左边的为 option ,等号右边的为 value
下面来一个demo:

            
              # -*- coding: utf-8 -*-
__author__ = "chenk"

import configparser


cf = configparser.ConfigParser()

# 读取配置文件
cf.read("config.ini")
print("获取所有配置项", cf.sections(), type(cf.sections()))
print("获取某一配置项的配置单元", cf.options("zhfx"), type(cf.options("zhfx")))
print("获取某一配置项详情的配置单元详情(返回结果为str)", cf.items("testdb"), type(cf.items("testdb")))
print("获取某一配置项的某一配置单元的值(返回结果为str)", cf.get("zhfx", "targets"), type(cf.get("zhfx", "targets")))
print("获取某一配置项的某一配置单元的值(返回结果为str)", cf.get("zhfx", "target"), type(cf.get("zhfx", "target")), "hello")
print("获取某一配置项的某一配置单元的值(返回结果为str)", cf.get("zhfx", "num"), type(cf.get("zhfx", "num")))
print("获取某一配置项的某一配置单元的值(返回结果为int)", cf.getint("zhfx", "num"), type(cf.getint("zhfx", "num")))


cf2 = configparser.ConfigParser()
# 增加配置项
cf2.add_section("add")
# 设置配置项
cf2.set("add", "str", "abc")
cf2.set("add", "str2", "123")   # 值仅允许str类型的
cf2.set("add", "str3", "111")   # 不允许 cf2.set("add", "str3", 111)
# 配置项写入文件
with open("config2.ini", "w") as f:
    cf2.write(f)

cf3 = configparser.ConfigParser()
cf3.read("config2.ini")
print(cf3.sections())
print(cf3.get("add", "str"), type(cf3.get("add", "str")))
print(cf3.get("add", "str2"), type(cf3.get("add", "str2")))
print(cf3.get("add", "str3"), type(cf3.get("add", "str3")))

            
          

上述 cf 对象,读取了 config.ini 的配置文件。展示了不同的获取配置文件的方式。 cf2 对象则增加了一个配置文件。 cf3 对象则读取了 cf2 新增的配置文件。总体来说,比较简单。需要注意一点的是,等号右侧的数据都是字符串。若设置的是整数类型,需要用 getint 的方法。
cf2 对象新增的配置文件如下:

            
              [add]
str = abc
str2 = 123
str3 = 111

            
          

更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论