From configparser import configparserfp = ' Conf.ini ' #定义配置文件名conf = Configparser () #实例化conf. Read (FP) # Open Confcon F.add_section (' Section1 ') #添加conf节点conf. Set (' Section1 ', ' name ', ' Jack ') #添加值conf. Set (' Section1 ', ' age ', ' 23 ') Conf.set (' Section1 ', ' worker ', ' CEO ') conf.add_section (' Section2 ') #添加conf节点conf. Set (' Section2 ', ' name ', ' Rose ') # Add Value conf.set (' Section2 ', ' age ', ' Max ') conf.set (' Section2 ', ' worker ', ' CCC ') with open (FP, ' W ') as FW: #循环写入 Conf.write (f W) ' [section1]name = Jackage = 23worker = CEO ' #读取配置文件from configparser import configparserfp = ' Conf.ini ' #定义配置文件名con f = Configparser () #实例化conf. Read (FP) # Open confname = Conf.get (' Section1 ', ' name ') print (name) "1" reads the configuration file read (filename ) Read the INI file directly sections () Get all the sections and return to the Options (section) in the form of a list to get all the Optionitems (section) of that section Get all the key values for the section get (section,option) Gets the value of option in section, and returns the value of the option in section for string type Getint (section,option). Returns the type int, with the corresponding Getboolean () and GetFloat () functions. "' Section= conf.sections () print (section) option =conf.options (' Section1 ') print (option) item=conf.items (' Section1 ') print (item) #改写操作conf. Set (' Section1 ', ' name ', ' Jackadam ') #设置为新值with open (FP, ' W ') as FW: #循环写入 Conf.write (FW) from Configparser import Configpars Er #重新读取fp = ' conf.ini ' #定义配置文件名conf = Configparser () #实例化conf. Read (FP) # Open confname = Conf.get (' Sectio N1 ', ' name ') print (name)
Python--configparser read/write config file