小编fbo*_*s66的帖子

Python:如何在省略注释的同时从属性文件创建字典

我已经在这里寻找了一段时间的答案并且没有找到它,所以希望这不是一个骗局.

我有一个属性文件,主要包含键=值对,但也包含#comments.我需要将它放在字典中,这样我就可以随意获取值.在没有#comments的文件中,以下工作完美.

myprops = dict(line.strip().split('=') for line in open('/Path/filename.properties'))
print myprops['key']
Run Code Online (Sandbox Code Playgroud)

但是当有评论出现时却不是这样.如果#comment存在,字典说

"ValueError: dictionary update sequence element #x has length 1, 2 is required"
Run Code Online (Sandbox Code Playgroud)

我试过用条件包装字典创建

if not line.startswith('#'):
Run Code Online (Sandbox Code Playgroud)

但我似乎无法让它发挥作用.建议?谢谢!

python dictionary properties-file

6
推荐指数
3
解决办法
1万
查看次数

标签 统计

dictionary ×1

properties-file ×1

python ×1