在Python中解析.properties文件

55 投票
10 回答
83246 浏览
提问于 2025-04-15 22:37

ConfigParser模块在解析简单的Java风格的.properties文件时会出现错误,这种文件的内容是键值对(也就是说,没有INI风格的章节标题)。有没有什么解决办法呢?

10 个回答

32

我的解决办法是使用 StringIO,并在前面加一个简单的虚拟头部:

import StringIO
import os
config = StringIO.StringIO()
config.write('[dummysection]\n')
config.write(open('myrealconfig.ini').read())
config.seek(0, os.SEEK_SET)

import ConfigParser
cp = ConfigParser.ConfigParser()
cp.readfp(config)
somevalue = cp.getint('dummysection', 'somevalue')
80

我觉得MestreLion的“read_string”评论很简单明了,值得给个例子。

对于Python 3.2及以上版本,你可以这样实现“虚拟部分”的想法:

with open(CONFIG_PATH, 'r') as f:
    config_string = '[dummy_section]\n' + f.read()
config = configparser.ConfigParser()
config.read_string(config_string)
80

假设你有,比如说:

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

也就是说,这会是一个 .config 格式,只不过缺少了开头的部分名称。那么,我们可以很简单地伪造一个部分标题:

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')]

撰写回答