Today, Python reads a configuration file with many fields, similar to the format in the configuration file:
Pidstart:2600startfid:47starttid:450startfirst:1message: "
It is common to think of:
Config = open (Configpath, ' R ') for item in config://set value one by one
Then think, so many fields how to set more tired, I think Python can be the string key directly as a variable how good, found: VARs ()
>>>STR = "abc" >>>vars () [str] = "TEST" >>>print (ABC) test
That this more cumbersome problem solved, the rest is to take the ":" Position, and then intercept the string, it is natural to use the slice operation:
IDX = Item.index (': ') s = Item[:idx]vars () [s] = item[(idx+1):].strip (' \ n ')
The full code:
Try:config = open ("Testconfig.ini", ' R ') for item in CONFIG:IDX = Item.index (': ') fname = Item[:idx] VARs () [fname] = item[(idx + 1):].strip (' \ n ') config.close () except Fileexistserror://do somethingexcept FILENOTF Ounderror://do somethingexcept:print (' Open config file error: ' + sys.exc_info () [0]) finally://do something
This article is from the "lybing" blog, make sure to keep this source http://lybing.blog.51cto.com/3286625/1823159
Python Variable Value transformation amount