When we write some test tools, often need to use to the configuration file, when the general choice of INI file is more appropriate
Standard and can be named by the parameter to know the meaning of the parameter, then how to use Python to read and write INI file?
First look at, read the INI file, we directly use the Python module Configparser to read and write the configuration file
Look at the code.
def readconfig (Configpath): configdict = {} CF = Configparser.configparser () cf.read (Configpath) Sessions = Cf.sections () for session in sessions: options = cf.options (session) for option in options: Key = Session + "." + option value = cf.get (session, option) configdict[key.lower ()] = value return configdic T
So through the above interface, we can read the configuration file into a Session.option=value dictionary, if you want to use, directly into the corresponding key can be
Then look at the INI file write, incoming parameters: To write the configuration file path, session node, option node, value values, in order to be consistent with the read interface, we use Key,value way to write
The code is as follows:
def writeconfig (Configpath, key, value): if Key.find (".") = =-1: return wsession = Key.split (".") [0] Woption = Key.split (".") [1] CF = Configparser.configparser () cf.read (Configpath) cf.set (wsession, woption, value) cf.write (open ( Configpath, "W"))
This allows you to modify the INI file in python ~
Reprint Please specify: Http://blog.csdn.net/sogouauto
Explore test art, Exchange test technology, Welcome to the "Sogou test"
Python writes the Read and write of an Automation INI file