Tag: Item key value pair class COM add div [] 127.0.0.1 Open
Write an. ini configuration file
Creates a new Config object, assigns a dictionary to the section, and then writes the file.
Import Configparserconfig=configparser. Configparser () config["DEFAULT"]={ ' ENGINE ': ' Django.db.backends.mysql ', ' HOST ': ' 127.0.0.1 ', ' PORT ': ' 3306 ', ' NAME ': ' Request ', ' USER ': ' Root ', ' PASSWORD ': ' 123456 ', ' OPTIONS ': { ' init_command ': ' SET sql_mode= ' strict_trans_tables ' " }}config[' django_setting ']={ ' ENGINE ': ' Django.db.backends.sqlite3 ', ' NAME ': ' Db.sqlite3 ', }with open ("Data.ini", "W") as FP: config.write (FP)
Reading configuration Files
Create a new Config object, read the configuration file, use the Get method or the dictionary to read the value of option under section
Import Configparserconfig=configparser. Configparser () config.read ("Data.ini") Keys=[]print (config["django_setting"]) #<section:django_setting >print (config.get (' Default ', ' Host ')) #127.0.0.1print (config[' default ' [' Host ']) #127.0.0.1for Key in config["Django_setting"]: keys.append (key) print (keys) #[' engine ', ' name ', ' Host ', ' Port ', ' user ', ' password ', ' Options ']print (Config.items ("DEFAULT")) #[(' engine ', ' Django.db.backends.mysql '), (' Host ', ' 127.0.0.1 '), (' Port ', ' 3306 '), (' name ', ' request '), (' User ', ' root '), (' Password ', ' 123456 '), (' Options ', ' {\ ' init_command\ ': "SET sql_m Ode=\ ' strict_trans_tables\ ' "} ')]
Changing the configuration file
Create a new Config object, read the configuration file, add_section new section,remove_section Delete section,remove_option move out of the key value pair in a section, Set adds or changes the value of an option in a section, and finally writes the configuration file
Import Configparserconfig=configparser. Configparser () config.read ("Data.ini") config.add_section ("new") Config.remove_section ("django_setting") Config.remove_option ("DEFAULT", "ENGINE") Config.set ("New", "ad", "123") with open ("Data1.ini", "W") as FP: Config.write (FP)
Python's Configparse module