標籤:option move 檔案內容 包含 style 路徑 val strong 資料
config parser —— 用於解析設定檔的模組
何為設定檔?
包含配置程式資訊的檔案就稱為設定檔
什麼樣的資料應該作為配置資訊
需要改 但是不經常改的資訊 例如:資料檔案的路徑
設定檔中 只有兩種內容:
一種是 section 分區
一種是 option 選項 就是一個 key=value 形式
我們用的最多的就是get功能 — 用來從設定檔擷取一個配置選項
執行個體如下:
# test.cfg 檔案內容如下:# 路徑相關的配置[path]db_path = C://myfile/test.txt# 使用者相關的配置[user]name = 高根# 服務相關的配置[server]url = 192.168.1.2
import configparser# 建立一個解析器config = configparser.ConfigParser()# 讀取並解析test.cfgconfig.read("test.cfg",encoding="utf-8")# 擷取需要的資訊# 擷取所有分區print(config.sections())擷取所有選項print(config.options("user"))擷取某個選項的值print(config.get("path","DB_PATH"))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)
config parser 模組