Python:如何在省略注释的情况下从属性文件创建字典 [英] Python: How to create a dictionary from properties file while omitting comments

查看:66
本文介绍了Python:如何在省略注释的情况下从属性文件创建字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在这里搜索答案了一段时间,但是没有找到它,所以希望这不是一个骗子.

I've searched for the answer to this here for awhile and haven't found it, so hope this isn't a dupe.

我有一个属性文件,其中大多数包含键=值对,但也包含#comments.我需要将其放入字典中,以便可以随意获取值.在没有#comments的文件中,以下内容可以完美地工作.

I have a properties file that mostly contains key=value pairs, but also contains #comments. I need to put it in a dictionary so I can grab values at will. In a file without #comments, the following works perfectly.

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

但是,当有评论存在时,情况并非如此.如果存在#comment,则字典会显示

But not so when there are comments present. If there's #comment present, dictionary says

"ValueError: dictionary update sequence element #x has length 1, 2 is required"

我尝试使用条件将字典创建包装在

I've tried wrapping the dictionary creation in conditionals with

if not line.startswith('#'):

但是我似乎无法使它正常工作.有什么建议吗?谢谢!

But I can't seem to get that to work. Suggestions? Thanks!

推荐答案

要解决关于空行的最新约束,我会尝试以下方法:

To address your newest constraint about blank lines, I would try something like:

myprops = {}
with open('filename.properties', 'r') as f:
    for line in f:
        line = line.rstrip() #removes trailing whitespace and '\n' chars

        if "=" not in line: continue #skips blanks and comments w/o =
        if line.startswith("#"): continue #skips comments which contain =

        k, v = line.split("=", 1)
        myprops[k] = v

这很清楚,而且很容易添加额外的约束,而使用dict理解会很肿.但是,您总是可以很好地格式化它

It's very clear and it's easy to add on extra constraints, whereas using a dict comprehension will get quite bloated. However, you could always format it nicely

myprops = dict(line.strip().split('=') 
               for line in open('/Path/filename.properties'))
               if ("=" in line and 
                   not line.startswith("#") and
                   <extra constraint> and
                   <another extra constraint>))

这篇关于Python:如何在省略注释的情况下从属性文件创建字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆