For more features, consider the user experience of the program, configuration features are essential, how to store the various configuration of the program?
1) Global variables can be used, but the global variables are volatile, the program crashes or shuts down after the configuration is gone, and the configuration is too many, where to assign variables to be considered.
2) with the configuration file, by reading the configuration file in the program to obtain the configuration, the user changes the configuration after the configuration file, even if the program crashes or shuts down, the configuration can still be saved.
3) Use the database to store configuration variables, but also long-term preservation, but read-write database is also a heavyweight operation, not very convenient.
Recently write a GUI program based on Wxpython, need to use the configuration file, originally intended to use XML files to store, read the Internet, read and write XML is also very troublesome, plus the program is small, not too complex configuration, consider a simple read and write files on the line, in the "Basic Python Tutorial second Edition "In the Configparser module, it is very simple. It's going to take it.
Using the Configparser module, the configuration file can be arbitrarily named, the only thing to note is that the content of the configuration file has the format requirements:
A configuration file is divided into sections, with the name of each section enclosed in brackets, and the variable and variable values below the brackets are separated by an equal sign.
Assuming that a configuration file is called Config.txt, the content format of the Config.txt should look like this:
[Numbers]
pi=3.1516926
maxfilesize=128*1024*1024
[MSG]
Error=sorry,an error occured.
Tipmsg=your input is invalid,please check and submit again.
How do I read and write configuration files with Configparser?
Load configuration file: Objconfigparser.read (filepath)
Read config variable: objconfigparser.get (section,variblename) or Objconfigparser.getint (section,variblename), if you know that the variable is of type int
Write (add) config variable to cache: Objconfigparser.set (section,variblename,newvalue),
Add a new Section:objConfigParser.add_section (sectionname)
Write the file for the modification to take effect: objconfigparser.write (Open (filepath, ' W '))
Sample program:
1 deftestconfig ():2configfile='.. /metadata/config.txt'3config=Configparser ()4Config.read (ConfigFile)#Load configuration file5 PrintConfig.getfloat ('numbers','Pi')#read the PI variable for section numbers6Config.set ('numbers','Pi', 3.14)#modifying PI variables7 #Create a new section8Config.add_section ('a_new_section')#Add a new section9Config.write (Open (ConfigFile,"W"))#Write File
Read and write the configuration file with the Configparser module--python