隨著腳本復雜程度增加, 配置文件成了必不可少。之前一直使用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元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
