首页 > 编程语言 > 详细

Python变量值转变量

时间:2016-07-11 01:13:14      阅读:144      评论:0      收藏:0      [点我收藏+]

今天用python读取一个有很多字段的配置文件,配置文件中的格式类似:

pidStart:2600
startFid:47
startTid:450
startFirst:1
message:‘‘

一般会想到的是:

config = open(configPath, ‘r‘)
for item in config:
    //set value one by one

然后就想了,这么多的字段怎么一个个的设置多累了,就想python可以将字符串key直接作为变量多好了,就找到了:vars()

>>>str = "abc"
>>>vars()[str] = "TEST"
>>>print(abc)
TEST

那这个比较繁琐的问题解决了,剩下的就是取":"的位置,然后截取字符串了,很自然的用到切片运算:

idx = item.index(‘:‘)
s = item[:idx]
vars()[s] = item[(idx+1):].strip(‘\n‘)


完整的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 something
except FileNotFoundError:
  //do something
except:
  print(‘Open config file error:‘+ sys.exc_info()[0])
finally:
  //do something


本文出自 “lybing” 博客,请务必保留此出处http://lybing.blog.51cto.com/3286625/1823159

Python变量值转变量

原文:http://lybing.blog.51cto.com/3286625/1823159

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!