在python中读取属性文件的快速方法是什么?
问题描述:
我有一个格式为
VarName=Value
.
.
我想将其读取为哈希,以便 H("VarName")
返回该值.
I want to read it into a hash such that H("VarName")
will return the value.
什么是快速的方法?(读取一组字符串,将所有字符串拆分成等号所在的位置,然后将其放入哈希中?
What would be a quick way? (read a set of strings, split all of them where the equality sign is, and then put it into a hash?
我正在使用python.
I am working with python.
答
一个班轮的答案:
H = dict(line.strip().split('=') for line in open('filename.txt'))
(如果值还可以包含"="字符,则可以选择将 .split()
与 maxsplit = 1
一起使用
(optionally use .split()
with maxsplit=1
if the values could also contain the "=" character)