yjhfgdfd 发表于 2016-7-11 09:03:17

Python变量值转变量

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


1
2
3
4
5
pidStart:2600
startFid:47
startTid:450
startFirst:1
message:''




一般会想到的是:

1
2
3
config = open(configPath, 'r')
for item in config:
    //set value one by one




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

1
2
3
4
>>>str = "abc"
>>>vars() = "TEST"
>>>print(abc)
TEST




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

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





完整的code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
try:
    config = open("testConfig.ini", 'r')
    for item in config:
      idx = item.index(':')
      fname = item[:idx]
      vars() = item[(idx + 1):].strip('\n')
config.close()
except FileExistsError:
//do something
except FileNotFoundError:
//do something
except:
print('Open config file error:'+ sys.exc_info())
finally:
//do something






页: [1]
查看完整版本: Python变量值转变量