在Python中解析键值的.properties文件

如果一个人解析了一个简单的Java风格的2746819449423660060032文件,该文件的内容是键-值对(即没有INI风格的节头),则2746819449423660060032模块将引发异常。 有一些解决方法吗?

tshepang asked 2020-02-14T06:15:02Z
10个解决方案
74 votes

说您有,例如:

$ 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')]
Alex Martelli answered 2020-02-14T06:19:35Z
42 votes

我认为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)
CoupleWavyLines answered 2020-02-14T06:20:02Z
32 votes

我的解决方案是使用27468248714172180180并添加一个简单的虚拟标头:

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')
tauran answered 2020-02-14T06:20:25Z
18 votes

Alex Martelli的上述回答不适用于Python 3.2+:readfp()已替换为read_file(),现在它需要一个迭代器而不是使用readline()方法。

这是使用相同方法的代码段,但可在Python 3.2+中使用。

>>> import configparser
>>> def add_section_header(properties_file, header_name):
...   # configparser.ConfigParser requires at least one section header in a properties file.
...   # Our properties file doesn't have one, so add a header to it on the fly.
...   yield '[{}]\n'.format(header_name)
...   for line in properties_file:
...     yield line
...
>>> file = open('my.props', encoding="utf_8")
>>> config = configparser.ConfigParser()
>>> config.read_file(add_section_header(file, 'asection'), source='my.props')
>>> config['asection']['first']
'primo'
>>> dict(config['asection'])
{'second': 'secondo', 'third': 'terzo', 'first': 'primo'}
>>>
Oscar de Groot answered 2020-02-14T06:20:50Z
5 votes

好极了! 另一个版本

基于此答案(添加内容使用ConfigParser.ini语句并支持%字符)

import ConfigParser
import StringIO
import os

def read_properties_file(file_path):
    with open(file_path) as f:
        config = StringIO.StringIO()
        config.write('[dummy_section]\n')
        config.write(f.read().replace('%', '%%'))
        config.seek(0, os.SEEK_SET)

        cp = ConfigParser.SafeConfigParser()
        cp.readfp(config)

        return dict(cp.items('dummy_section'))

用法

props = read_properties_file('/tmp/database.properties')

# It will raise if `name` is not in the properties file
name = props['name']

# And if you deal with optional settings, use:
connection_string = props.get('connection-string')
password = props.get('password')

print name, connection_string, password

我的示例中使用的ConfigParser文件

name=mongo
connection-string=mongodb://...
password=my-password%1234

编辑2015-11-06

感谢Neill Lima提到ConfigParser字符存在问题。

这样做的原因是ConfigParser设计为解析.ini文件。 %字符是一种特殊语法。 为了使用%字符,只需根据.ini语法用%%添加一个替换为%

Jossef Harush answered 2020-02-14T06:21:38Z
4 votes
with open('some.properties') as file:
    props = dict(line.strip().split('=', 1) for line in file)

归功于如何从文本文件创建包含键值对的字典

如果值中有相等的符号,则maxsplit=1很重要(例如someUrl=https://some.site.com/endpoint?id=some-value&someotherkey=value

user9192156 answered 2020-02-14T06:22:04Z
1 votes

该答案建议在Python 3中使用itertools.chain。

from configparser import ConfigParser
from itertools import chain

parser = ConfigParser()
with open("foo.conf") as lines:
    lines = chain(("[dummysection]",), lines)  # This line does the trick.
    parser.read_file(lines)
Christian Long answered 2020-02-14T06:22:25Z
1 votes
from pyjavaproperties import Properties
p = Properties()
p.load(open('test.properties'))
p.list()
print p
print p.items()
print p['name3']
p['name3'] = 'changed = value'
print p['name3']
p['new key'] = 'new value'
p.store(open('test2.properties','w'))
Andy Quiroz answered 2020-02-14T06:27:03Z
-1 votes
with open('mykeyvaluepairs.properties') as f:
    defaults = dict([line.split() for line in f])
config = configparser.ConfigParser(defaults)
config.add_section('dummy_section')

现在config.get('properties', option)将从DEFAULT部分返回'option'。

要么:

with open('mykeyvaluepairs.properties') as f:
    properties = dict([line.split() for line in f])
config = configparser.ConfigParser()
config.add_section('properties')
for prop, val in properties.items():
    config.set('properties', prop, val)

在这种情况下,config.get('properties', option)不求助于默认部分。

Scruffy answered 2020-02-14T06:27:32Z
-1 votes

基于Alex Martelli的答案的python2.7的另一个答案

import ConfigParser

class PropertiesParser(object):

    """Parse a java like properties file

    Parser wrapping around ConfigParser allowing reading of java like
    properties file. Based on stackoverflow example:
    https://stackoverflow.com/questions/2819696/parsing-properties-file-in-python/2819788#2819788

    Example usage
    -------------
    >>> pp = PropertiesParser()
    >>> props = pp.parse('/home/kola/configfiles/dev/application.properties')
    >>> print props

    """

    def __init__(self):
        self.secheadname = 'fakeSectionHead'
        self.sechead = '[' + self.secheadname + ']\n'

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

    def parse(self, filepath):
        self.fp = open(filepath)
        cp = ConfigParser.SafeConfigParser()
        cp.readfp(self)
        self.fp.close()
        return cp.items(self.secheadname)
KolaB answered 2020-02-14T06:27:54Z
translate from https://stackoverflow.com:/questions/2819696/parsing-properties-file-in-python