Python中的属性文件(类似于Java属性)
给定以下格式(.properties 或 .ini):
propertyName1=propertyValue1
propertyName2=propertyValue2
...
propertyNameN=propertyValueN
在 Java 中,有一个叫做 Properties 的类,可以用来解析和处理上面的格式。
那么在 python 的 标准 库(2.x 版本)中,有类似的东西吗?
如果没有,还有什么其他的选择呢?
28 个回答
79
我知道这个问题很老旧,但我现在需要它,所以我决定自己实现一个解决方案,这是一个纯Python的解决方案,能够处理大部分的使用情况(虽然不是全部):
def load_properties(filepath, sep='=', comment_char='#'):
"""
Read the file passed as parameter as a properties file.
"""
props = {}
with open(filepath, "rt") as f:
for line in f:
l = line.strip()
if l and not l.startswith(comment_char):
key_value = l.split(sep)
key = key_value[0].strip()
value = sep.join(key_value[1:]).strip().strip('"')
props[key] = value
return props
你可以把 sep
改成 ':' 来解析格式为:
key : value
这段代码可以正确解析像这样的行:
url = "http://my-host.com"
name = Paul = Pablo
# This comment line will be ignored
你会得到一个字典,里面包含:
{"url": "http://my-host.com", "name": "Paul = Pablo" }
98
试试 ConfigParser
我成功用 ConfigParser
实现了这个功能,之前没有人给出过相关的例子,所以我这里分享一个简单的 Python 程序,用来读取属性文件,以及属性文件的示例。请注意,文件的扩展名仍然是 .properties
,但我需要添加一个类似于 .ini 文件中的部分标题……虽然有点不太规范,但确实能用。
这个 Python 文件是: PythonPropertyReader.py
#!/usr/bin/python
import ConfigParser
config = ConfigParser.RawConfigParser()
config.read('ConfigFile.properties')
print config.get('DatabaseSection', 'database.dbname');
属性文件是: ConfigFile.properties
[DatabaseSection]
database.dbname=unitTest
database.user=root
database.password=
想了解更多功能,可以查看: https://docs.python.org/2/library/configparser.html
76
对于 .ini
文件,有一个叫做 configparser
的模块,它可以处理和 .ini
文件兼容的格式。
不过,目前没有现成的工具可以用来解析完整的 .properties
文件。当我需要处理这些文件时,我通常会使用 jython(我指的是脚本编写)。