码迷,mamicode.com
首页 > 编程语言 > 详细

Python变量值转变量

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

标签:python   文件   open()   切片   

今天用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变量值转变量

标签:python   文件   open()   切片   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!