The configpraser of the Python module
I. Configpraser INTRODUCTION
The file used to process a particular format, essentially using open to manipulate the file.
Format of the configuration file:
Use "[]" to include configuration content similar to Key-value under Section,section (for example: Samba profile)
G:\Python project actual combat \ Module \configparser>start example.txt #基于windows平台
# Note 1; note 2[global] # node workgroup = Workgroup # value (key-value) = Share
= Stuff= True
PI = 3.1415926
Two. Configpraser initialization
You must first initialize and read the configuration file when you use it
Import= configparser. Configparser () config.read ('example.txt', encoding='utf-8' )
Three. Configpraser Common methods
1. Get all nodes:
ret = config.sections () # reads all the "[]" messages in the configuration file print# output: ['global' public']
2. Gets all the key-value pairs under the specified node:
ret = Config.items ('Global')#gets all the key-value pairs for the specified nodePrint(ret)#Output:[('Workgroup','WORKGROUP'), ('Security','Share'), ('Maxlog',' -')]
3. Gets all the keys under the specified node:
ret = config.options ('public')# All keys under the specified node print(ret) # output:['comment' Public ' ' Pi ']
4. Gets the value of the specified key under the specified node:
ret = Config.get ('global','workgroup')# Gets the value of key under the specified node # ret = config.getint (' Global ', ' Maxlog ') #获取指定节点下key值, must be an integer otherwise error # ret = config.getfloat (' Public ', ' pi ') #获取指定节点下key值, must be a floating-point number otherwise error # ret = Config.getboolean (' Public ', ' public ') #获取指定节点下key值, must be a Boolean value otherwise error Print (ret)
5. Checking, adding, deleting nodes
#CheckCheck = Config.has_section ('Global')#Check if there is a value under this node, return a Boolean valuePrint(check)#Output:True#Adding nodesConfig.add_section ('Local')#Add to MemoryConfig.write (Open ('Example.txt','W'))#write in FileRET =config.sections ()Print(ret)#Output:['Global',' Public','Local']#Delete a nodeConfig.remove_section ('Local')#Delete a nodeConfig.write (Open ('Example','W'))#re-write fileRET =config.sections ()Print(ret)#Output:['Global',' Public']
6. Check, delete, set the key value pair within the specified group
#CheckCheck = Config.has_option (' Public','Comment')#check a key under the node to return a Boolean valuePrint(check) output: True#DeleteConfig.remove_option ('Global','Workgroup') config.write (open ('Example.txt','W')) RET= Config.options ('Global')Print(ret)#Output:['Security','Maxlog']#sets the key-value pair within the specified nodeRet1 = Config.get ('Global','Maxlog')Print(RET1) Config.set ('Global','Maxlog',' -') config.write (open ('Example.txt','W')) Ret2= Config.get ('Global','Maxlog')Print(Ret2)#Output:50100
The configpraser of the Python module