Configparse modules are commonly used to generate and modify common configuration documents
Build configuration module: write in a dictionary
Import Configparserconfig = Configparser. Configparser () config["DEFAULT"] = {' Serveraliveinterval ': ' A ', ' Compression ': ' Yes ', ' compressionlevel ': ' 9 '}config[' user '] = {}config[' user ' [' user '] = ' hhh ' config[' ssh '] = {}topsecret = config[' ssh ']topsecret[' Host Port '] = ' 50022 ' # mutates the parsertopsecret[' ForwardX11 '] = ' no ' # same hereconfig[' DEFAULT ' [' ForwardX11 '] = ' yes ' With open (' Example.ini ', ' W ') as ConfigFile: config.write (ConfigFile)
Read configuration: Config.sections ()
Import Configparserconfig = Configparser. Configparser () config.read (' Example.ini ') print (Config.sections ()) # [' USER ', ' SSH '], default not Dayin[default] Module print (config[' user ') # <section:user>print (config[' user ' [' user ']) # Hgprint (Config.defaults ()) # Print default module, print out an ordered dictionary of print (config.has_section (' USER ')) # True ordereddictprint (config[' default '] [' CompressionLevel '] # 9 # Print the default module, print out an ordered dictionary ordereddict#, like a dictionary, prints only key information for key in config[' default ': # print ( Key, V) error, too many values to unpack (expected 2) print (key)
Delete Entire module: Remove, file cannot be modified, only overwrite, can be re-written to new file
Import Configparserconfig = Configparser. Configparser () config.read (' Example.ini ') # file cannot be modified, only overwritten, can be re-written to new file Config.remove_section (' SSH ') with open (' Example.ini ', ' W ', encoding= ' utf-8 ') as F: Config.write (f) Print (Config.sections ())
Delete an element under a module
Import Configparserconfig = Configparser. Configparser () config.read (' Example.ini ') print (config.has_option (' User ', ' user ') config.remove_option (' User ', ' User ') print (config.has_option (' User ', ' user ')) with open (' Example.ini ', ' W ', encoding= ' utf-8 ') as F: Config.write (f)
To modify the configuration:
Import Configparserconfig = Configparser. Configparser () config.read (' Example.ini ') print (config[' user ' [' user ']) config.set (' User ', ' user ', ' FTL ') print ( config[' user ' [' user ']) with open (' Example.ini ', ' W ', encoding= ' utf-8 ') as F: Config.write (f)
The configparse of the key modules of Python learning---