Python Variable Value transformation amount

Source: Internet
Author: User
Tags vars

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.