config parser 模組

來源:互聯網
上載者:User

標籤: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 模組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.