1. 程式人生 > >configparser的使用去操作配置檔案

configparser的使用去操作配置檔案

import configparser   #寫配置檔案

config = configparser.ConfigParser()  #有了一個空字典 config = {}

config["DEFAULT"] = {"yishu":"27"}   #defalut操作和字典一樣,給鍵值對

config["bitcome"] = {}  #如果想建立新的配置型別,你要給它名字,先建立一個新的字典,再往裡面新增鍵值對
config["bitcome"]["good"] = "fds"
config["bitcome"]["gold"] = "gfdg"


with open("example.init","w") as f:
    config.write(f)

config.read("example.init")

print(config.sections())   #只打印除default的配置
print("bitcome" in config)  #判斷是否在檔案中
print(config["bitcome"]['good'])  #列印good鍵有沒有值
print(config["bitcome"]["yishu"])

for key in config['bitcome']:
    print(key)   #遍歷鍵  #good gold yishu

#default鍵,裡面的鍵可以和其他的一起遍歷出來。比如上面遍歷bitcome會出現yishu
#幹什麼用的呢  如果default中存入公司名稱,那麼這個必須的鍵值就隨著其他的被打印出來

print(config.options('bitcome'))   #['good', 'gold', 'yishu'] 以列表形式打印出包含的鍵
print(config.items('bitcome'))  #[('yishu', '27'), ('good', 'fds'), ('gold', 'gfdg')]  鍵值配對成元祖
print(config.get("bitcome","good"))  #fds

#----------------刪改增------------------------------

config.read("example.init")
config.add_section('yuan')   #加一個塊
config.set('yuan','k1','111')  #往這個塊中加鍵,值,順序,比較好記
config.remove_section("")  #刪除塊
config.remove_option("bitcome","good")  #刪除某個塊的某個鍵值對

config.write(open('example.init',"w"))  #這種寫法不用關閉