1. 程式人生 > >python configparser模塊的應用

python configparser模塊的應用

item move AR 分隔 not section 指定 windows set方法

import configparser
"""
“[ ]”包含的為 section,section 下面為類似於 key - value 的配置內容;
configparser 默認支持 ‘=’ ‘:’ 兩種分隔。

ConfigParser模塊在python3中修改為configparser.這個模塊定義了一個ConfigParser類,
該類的作用是使用配置文件生效,配置文件的格式和windows的INI文件的格式相同.conf
"""
#初始化實例
config = configparser.ConfigParser() #註意大小寫
#先要讀取配置文件
config.read("test.ini")
# 獲取所有的sections
config.sections() # 返回值為列表[‘test1‘, ‘test2‘, ‘test3‘] ,會過濾掉 ["DEFAULT"]
# 獲取指定section的key value (註意key會全部變為小寫,而value不會)
config.items(‘test1‘) # [(‘money‘, ‘100‘), (‘name‘, ‘WangFuGui‘), (‘age‘, ‘20‘)]
# 獲取指定section的keys name變為小寫
config.options("test1") # [‘name‘, ‘age‘, ‘money‘]
# 獲取指定的key的value name 大小寫均可以 value默認為字符
config["test1"]["Name"] # WangFuGui
config.get("test1","name") # WangFuGui
config.getint("test1","age") # 100 轉換為int 類型
# 檢查
"DEFAULT" in config # True
"100"in config["test1"]["money"] # True
# 添加
if "add_section1" not in config:
config.add_section("add_section1")
config.set("add_section1","hobby","game") #用set方法
config.write(open("test.ini","w")) # 一定要寫入才生效
# 移除
config.remove_option("add_section1","hobby")
config.remove_section("add_section1")
config.write(open(‘test.ini‘,"w")) # 一定要寫入才生效

python configparser模塊的應用