随着脚本复杂程度增加, 配置文件成了必不可少。之前一直使用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