python--configparser
阿新 • • 發佈:2018-03-06
conf pri alt 配置文件 close post val 特定 lap
configparser 是Python自帶的模塊, 用來讀寫配置文件。
特定的格式:
1 # 註釋1 2 ; 註釋2 3 [Node1] #節點 4 key1=value1 #鍵值 5 ... 6 7 [Node2] ;節點 8 key2=value2 ;節點 9 ...格式
用法:
1 import configparser 2 3 #創建一個configparser對象 4 config=configparser.ConfigParser() 5 #將特定格式的配置文件加載到內存中 6 config.read("node.txtconfigparser用法",encoding="utf-8") 7 #或者所有的節點 8 node=config.sections() 9 print(node) 10 11 #獲取指定的鍵 12 allKey=config.options("Node1") 13 print(allKey) 14 15 #獲取指定節點下面的key的值 16 key=config.get("Node2","key2") 17 print(key) 18 19 #添加節點 20 config.add_section("node3") 21 22 #刪除節點 23 config.remove_section("Node1") 2425 #檢查是否有節點 26 hasNode=config.has_section("Node1") 27 print(hasNode) 28 29 #檢查指定組內的鍵值對 30 hasKeyValue=config.has_option("Node1","key1") 31 print(hasKeyValue) 32 #刪除指定組內的鍵值對 33 delKeyValue=config.remove_option("Node2","key2") 34 print(delKeyValue) 35 #設置指定組內的鍵值對 36 config.set("Node3","key4","value4") 37 38 39 #將修改後的配置文件寫到文件中 40 config.write(open("node.txt","w",encoding="utf-8"))
python--configparser