1. 程式人生 > >常用模組——configparser模組

常用模組——configparser模組

configparser模組

用於解析配置檔案的模組
何為配置檔案
包含配置程式資訊的檔案就稱為配置檔案
什麼樣的資料應作為配置資訊
需要改 但是不經常改的資訊 例如資料檔案的路徑 DB_PATH

配置檔案中 只有兩種內容

種是section 分割槽
一種是option 選項 就是一個key=value形式
我們用的最多的就是get功能 用來從配置檔案獲取一個配置選項

讀取cfg檔案的步驟
#建立一個解析器
config = configparser.ConfigParser()
# 讀取並解析test.cfg
config.read('test.cfg',encoding='
utf-8')
#獲得分割槽
print(config.sections())
#獲得’path'分割槽下選項
print(config.options('path'))
#['path', 'user']
#['dp_file']
#獲取某分割槽的某選項的值
print(config.get("path","dp_file"))
print(type(config.get("user","age")))
# # get返回的都是字串型別  如果需要轉換型別 直接使用get+對應的型別(bool int float)
print(type(config.getint("
user","age"))) print(type(config.get("user","age")))

不常用

# 是否由某個選項
config.has_option()
# 是否由某個分割槽
config.has_section()
# 新增
config.add_section("server")
config.set("server","url","192.168.1.2")
# 刪除
config.remove_option("user","age")
# 修改
config.set("server","url","192.168.1.2
")
# 寫回檔案中
with open("test.cfg", "wt", encoding="utf-8") as f:
    config.write(f)