在Python中解析.properties文件 [英] parsing .properties file in Python

查看:653
本文介绍了在Python中解析.properties文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ConfigParser 模块会引发异常,如果一个人解析了一种简单的Java样式 .properties 文件,其内容为键值对(即不包含INI样式的节标题).有什么解决方法吗?

The ConfigParser module raises an exception if one parses a simple Java-style .properties file, whose content is key-value pairs (i..e without INI-style section headers). Is there some workaround?

推荐答案

说,例如:

$ cat my.props
first: primo
second: secondo
third: terzo

即将为.config格式,但缺少前导部分名称.然后,很容易伪造节标题:

i.e. would be a .config format except that it's missing a leading section name. Then, it easy to fake the section header:

import ConfigParser

class FakeSecHead(object):
    def __init__(self, fp):
        self.fp = fp
        self.sechead = '[asection]\n'

    def readline(self):
        if self.sechead:
            try: 
                return self.sechead
            finally: 
                self.sechead = None
        else: 
            return self.fp.readline()

用法:

cp = ConfigParser.SafeConfigParser()
cp.readfp(FakeSecHead(open('my.props')))
print cp.items('asection')

输出:

[('second', 'secondo'), ('third', 'terzo'), ('first', 'primo')]

这篇关于在Python中解析.properties文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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