python configparser库简介

随着脚本复杂程度增加, 配置文件成了必不可少。之前一直使用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
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值