Python3 INI file read and write
ini is a file extension in Microsoft Windows operating system (also commonly used in other systems).
ini is one of the configuration file formats we commonly see.
ini is a file extension in Microsoft Windows operating system (also commonly used in other systems).
ini is an abbreviation of "Initial". As the term implies, INI files are used to initialize or set parameters for the operating system or specific programs.
Its basic composition is as follows:
[ section_1 ]
key1 = value1
key2 = value2
key3 = value3
key4 = value4
[ section_2 ]
key1 = value1
key2 = value2
key3 = value3
key4 = value4
We use Python's ConfigParser module to read and write ini files.
ConfigParser
Read
- read(filename) read the contents of the ini file
- sections() Get all the sections and return them as a list
- options(sections) Get all options of the specified section
- get(section,option) Get the value of option in section, and return it as string type
Write
- set(section, option, value) updates the option in the section
Instance
We first generate an ini file, write the data, and then display it after reading it.
# - * - coding : utf -8 - * -
__author__ = 'Bitter leaves'
# Import module
import configparser
if __name__ == "__main__" :
# First build an object
config = configparser . ConfigParser ( )
# Let us write a few sets of data
# First add a section
config . add_section ( "Open Source Test" )
# Add key - value key - value pairs under the newly added section
config . set ( "open source excellent test" , "micro account " , "DeepTest" )
config . set ( "open source excellent test" , "slogan" , "self-entertainment" )
config . set ( "open source excellent test" , " Extra number" , "Actually I opened a lot of numbers" )
# Add another section without adding key - value key - value pairs
config . add_section ( "I'm so lonely" )
# Write file
with open ( 'iniConfig.ini' , 'w' ) as configfile :
config . write ( configfile )
###################################
# Let’s read out the ini file just now.
config . read ( "iniConfig.ini" )
# Get all its sections
Sections = config . Sections ( )
Print ( Sections )
# Get all the options under the section
for sec in sections :
options = config . options ( sec )
print ( options )
# Get the corresponding value value according to sections and options
for sec in sections :
for option in config . options ( sec ) :
print ( "[%s] %s=%s " % ( sec , option , config . get ( sec , option ) ) )
summary
For INI file application scenarios, it is generally used as an initialization configuration file, of course, you can also use it for data storage if you want.