149

给定以下格式(.properties.ini):

propertyName1=propertyValue1
propertyName2=propertyValue2
...
propertyNameN=propertyValueN

对于JavaProperties类提供了解析/与上述格式交互的功能。

python标准库(2.x)中是否有类似的东西?

如果没有,我还有什么其他选择?

4

25 回答 25

86

我能够让它工作ConfigParser,没有人展示任何关于如何做到这一点的例子,所以这里是一个简单的属性文件的python阅读器和属性文件的例子。请注意,扩展名仍然是.properties,但我必须添加一个类似于您在 .ini 文件中看到的部分标题......有点混蛋,但它有效。

蟒蛇文件: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

于 2014-10-06T16:59:40.040 回答
74

对于.ini文件,有configparser提供与文件兼容的格式的模块.ini

无论如何,没有任何东西可用于解析完整的.properties文件,当我不得不这样做时,我只需使用 jython(我说的是脚本)。

于 2010-08-29T15:39:56.700 回答
67

我知道这是一个非常古老的问题,但我现在才需要它,我决定实现我自己的解决方案,一个纯 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" }
于 2015-08-06T09:47:06.277 回答
64

Java 属性文件通常也是有效的 Python 代码。您可以将 myconfig.properties 文件重命名为 myconfig.py。然后只需导入您的文件,就像这样

import myconfig

并直接访问属性

print myconfig.propertyName1
于 2011-11-22T01:13:13.900 回答
17

如果您可以选择文件格式,我建议使用 .ini 和 Python 的 ConfigParser,如前所述。如果您需要与 Java .properties 文件兼容,我已经为它编写了一个名为jprops的库。我们使用的是 pyjavaproperties,但在遇到各种限制后,我最终实现了自己的。它完全支持 .properties 格式,包括 unicode 支持和对转义序列的更好支持。Jprops 还可以解析任何类似文件的对象,而 pyjavaproperties 仅适用于磁盘上的真实文件。

于 2011-11-30T01:16:25.880 回答
16

如果你没有多行属性和一个非常简单的需求,几行代码就可以为你解决:

文件t.properties

a=b
c=d
e=f

Python代码:

with open("t.properties") as f:
    l = [line.split("=") for line in f.readlines()]
    d = {key.strip(): value.strip() for key, value in l}
于 2018-07-10T10:47:20.887 回答
6

这不完全是属性,但 Python 确实有一个很好的库来解析配置文件。另请参阅此配方:java.util.Properties 的 python 替代品

于 2010-08-29T15:38:43.990 回答
6

我用过这个,这个库非常有用

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'
于 2019-02-12T23:02:59.130 回答
4

这是我的项目的链接:https ://sourceforge.net/projects/pyproperties/ 。它是一个库,其中包含处理 Python 3.x 的 *.properties 文件的方法。

但它不是基于 java.util.Properties

于 2012-10-28T20:51:11.820 回答
3

是 java.util.Propeties 的一对一替换

从文档:

  def __parse(self, lines):
        """ Parse a list of lines and create
        an internal property dictionary """

        # Every line in the file must consist of either a comment
        # or a key-value pair. A key-value pair is a line consisting
        # of a key which is a combination of non-white space characters
        # The separator character between key-value pairs is a '=',
        # ':' or a whitespace character not including the newline.
        # If the '=' or ':' characters are found, in the line, even
        # keys containing whitespace chars are allowed.

        # A line with only a key according to the rules above is also
        # fine. In such case, the value is considered as the empty string.
        # In order to include characters '=' or ':' in a key or value,
        # they have to be properly escaped using the backslash character.

        # Some examples of valid key-value pairs:
        #
        # key     value
        # key=value
        # key:value
        # key     value1,value2,value3
        # key     value1,value2,value3 \
        #         value4, value5
        # key
        # This key= this value
        # key = value1 value2 value3

        # Any line that starts with a '#' is considerered a comment
        # and skipped. Also any trailing or preceding whitespaces
        # are removed from the key/value.

        # This is a line parser. It parses the
        # contents like by line.
于 2011-06-29T21:35:16.020 回答
3

在您的 python 模块中创建一个字典并将所有内容存储到其中并访问它,例如:

dict = {
       'portalPath' : 'www.xyx.com',
       'elementID': 'submit'}

现在要访问它,您只需执行以下操作:

submitButton = driver.find_element_by_id(dict['elementID'])
于 2019-06-18T16:18:25.853 回答
3

如果您需要以简单的方式从属性文件中的某个部分读取所有值:

您的config.properties文件布局:

[SECTION_NAME]  
key1 = value1  
key2 = value2  

你编码:

   import configparser

   config = configparser.RawConfigParser()
   config.read('path_to_config.properties file')

   details_dict = dict(config.items('SECTION_NAME'))

这将为您提供一个字典,其中键与配置文件中的键及其对应的值相同。

details_dict是 :

{'key1':'value1', 'key2':'value2'}

现在获取 key1 的值: details_dict['key1']

将其全部放入一个仅从配置文件中读取该部分一次的方法中(在程序运行期间第一次调用该方法)。

def get_config_dict():
    if not hasattr(get_config_dict, 'config_dict'):
        get_config_dict.config_dict = dict(config.items('SECTION_NAME'))
    return get_config_dict.config_dict

现在调用上述函数并获取所需键的值:

config_details = get_config_dict()
key_1_value = config_details['key1'] 

-------------------------------------------------- ------------

扩展上面提到的方法,自动逐段读取,然后按段名后跟键名访问。

def get_config_section():
    if not hasattr(get_config_section, 'section_dict'):
        get_config_section.section_dict = dict()

        for section in config.sections():
            get_config_section.section_dict[section] = 
                             dict(config.items(section))

    return get_config_section.section_dict

访问:

config_dict = get_config_section()

port = config_dict['DB']['port'] 

(这里的“DB”是配置文件中的部分名称,“port”是“DB”部分下的键。)

于 2017-01-17T09:32:41.610 回答
3

我的 Java ini 文件没有节标题,因此我想要一个 dict。所以我只是注入了一个“[ini]”部分,让默认配置库完成它的工作。

以eclipse IDE.metadata目录的version.ini文件为例:

#Mon Dec 20 07:35:29 CET 2021
org.eclipse.core.runtime=2
org.eclipse.platform=4.19.0.v20210303-1800
# 'injected' ini section
[ini]
#Mon Dec 20 07:35:29 CET 2021
org.eclipse.core.runtime=2
org.eclipse.platform=4.19.0.v20210303-1800

结果被转换为字典:

from configparser import ConfigParser

@staticmethod
    def readPropertyFile(path):
        # https://stackoverflow.com/questions/3595363/properties-file-in-python-similar-to-java-properties
        config = ConfigParser()
        s_config= open(path, 'r').read()
        s_config="[ini]\n%s" % s_config
        # https://stackoverflow.com/a/36841741/1497139
        config.read_string(s_config)
        items=config.items('ini')
        itemDict={}
        for key,value in items:
            itemDict[key]=value
        return itemDict
于 2020-11-01T10:09:01.873 回答
3

您可以使用ConfigParser.RawConfigParser.readfp此处定义的类文件对象-> https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.readfp

定义一个覆盖readline在属性文件的实际内容之前添加节名称的类。

我已将它打包到返回dict所有已定义属性的类中。

import ConfigParser

class PropertiesReader(object):

    def __init__(self, properties_file_name):
        self.name = properties_file_name
        self.main_section = 'main'

        # Add dummy section on top
        self.lines = [ '[%s]\n' % self.main_section ]

        with open(properties_file_name) as f:
            self.lines.extend(f.readlines())

        # This makes sure that iterator in readfp stops
        self.lines.append('')

    def readline(self):
        return self.lines.pop(0)

    def read_properties(self):
        config = ConfigParser.RawConfigParser()

        # Without next line the property names will be lowercased
        config.optionxform = str

        config.readfp(self)
        return dict(config.items(self.main_section))

if __name__ == '__main__':
    print PropertiesReader('/path/to/file.properties').read_properties()
于 2017-05-18T03:19:59.600 回答
2

这就是我在我的项目中所做的:我只是创建了另一个名为 properties.py 的 .py 文件,其中包括我在项目中使用的所有公共变量/属性,并且在任何文件中都需要引用这些变量,把

from properties import *(or anything you need)

当我经常更改开发位置并且一些常见变量与本地环境相当相关时,使用此方法来保持 svn 和平。对我来说很好,但不确定这种方法是否会被建议用于正式的开发环境等。

于 2012-12-12T05:30:14.103 回答
2
import json
f=open('test.json')
x=json.load(f)
f.close()
print(x)

test.json 的内容: {"host": "127.0.0.1", "user": "jms"}

于 2016-06-02T16:27:00.753 回答
2

我创建了一个几乎类似于 Java 的 Properties 类的 python 模块(实际上它就像 Spring 中的 PropertyPlaceholderConfigurer ,它允许您使用 ${variable-reference} 来引用已定义的属性)

编辑:您可以通过运行命令来安装此软件包(目前已针对 python 3 进行了测试)。
pip install property

该项目托管在GitHub 上

示例:(可以在此处找到详细文档)

假设您在 my_file.properties 文件中定义了以下属性

foo = I am awesome
bar = ${chocolate}-bar
chocolate = fudge

加载上述属性的代码

from properties.p import Property

prop = Property()
# Simply load it into a dictionary
dic_prop = prop.load_property_files('my_file.properties')
于 2016-05-28T18:39:49.400 回答
1

您可以使用参数“fromfile_prefix_chars”和argparse从配置文件中读取如下---

临时文件

parser = argparse.ArgumentParser(fromfile_prefix_chars='#')
parser.add_argument('--a')
parser.add_argument('--b')
args = parser.parse_args()
print(args.a)
print(args.b)

配置文件

--a
hello
--b
hello dear

运行命令

python temp.py "#config"
于 2020-05-12T16:57:14.777 回答
1

下面 2 行代码展示了如何使用 Python 列表理解来加载“java 样式”属性文件。

split_properties=[line.split("=") for line in open('/<path_to_property_file>)]
properties={key: value for key,value in split_properties }

有关详细信息,请查看以下帖子 https://ilearnonlinesite.wordpress.com/2017/07/24/reading-property-file-in-python-using-comprehension-and-generators/

于 2017-07-27T20:28:14.403 回答
0

我使用 ConfigParser 执行此操作,如下所示。该代码假定在放置 BaseTest 的同一目录中有一个名为 config.prop 的文件:

配置文件

[CredentialSection]
app.name=MyAppName

基础测试.py:

import unittest
import ConfigParser

class BaseTest(unittest.TestCase):
    def setUp(self):
        __SECTION = 'CredentialSection'
        config = ConfigParser.ConfigParser()
        config.readfp(open('config.prop'))
        self.__app_name = config.get(__SECTION, 'app.name')

    def test1(self):
        print self.__app_name % This should print: MyAppName
于 2015-06-11T15:09:31.167 回答
0

这是我编写的解析文件并将其设置为跳过注释和非键值行的 env 变量添加了开关以指定 hg:d

  • -h 或 --help 打印使用摘要
  • -c 指定标识注释的字符
  • -s 属性文件中键和值之间的分隔符
  • 并指定需要解析的属性文件,例如:python EnvParamSet.py -c # -s = env.properties

    import pipes
    import sys , getopt
    import os.path
    
    class Parsing :
    
            def __init__(self , seprator , commentChar , propFile):
            self.seprator = seprator
            self.commentChar = commentChar
            self.propFile  = propFile
    
        def  parseProp(self):
            prop = open(self.propFile,'rU')
            for line in prop :
                if line.startswith(self.commentChar)==False and  line.find(self.seprator) != -1  :
                    keyValue = line.split(self.seprator)
                    key =  keyValue[0].strip() 
                    value = keyValue[1].strip() 
                            print("export  %s=%s" % (str (key),pipes.quote(str(value))))
    
    
    
    
    class EnvParamSet:
    
        def main (argv):
    
            seprator = '='
            comment =  '#'
    
            if len(argv)  is 0:
                print "Please Specify properties file to be parsed "
                sys.exit()
            propFile=argv[-1] 
    
    
            try :
                opts, args = getopt.getopt(argv, "hs:c:f:", ["help", "seprator=","comment=", "file="])
            except getopt.GetoptError,e:
                print str(e)
                print " possible  arguments  -s <key value sperator > -c < comment char >    <file> \n  Try -h or --help "
                sys.exit(2)
    
    
            if os.path.isfile(args[0])==False:
                print "File doesnt exist "
                sys.exit()
    
    
            for opt , arg  in opts :
                if opt in ("-h" , "--help"):
                    print " hg:d  \n -h or --help print usage summary \n -c Specify char that idetifes comment  \n -s Sperator between key and value in prop file \n  specify file  "
                    sys.exit()
                elif opt in ("-s" , "--seprator"):
                    seprator = arg 
                elif opt in ("-c"  , "--comment"):
                    comment  = arg
    
            p = Parsing( seprator, comment , propFile)
            p.parseProp()
    
        if __name__ == "__main__":
                main(sys.argv[1:])
    
于 2016-09-01T09:40:32.637 回答
0

可以使用下面的函数,就是@mvallebr的修改代码。它尊重属性文件注释,忽略空的新行,并允许检索单个键值。

def getProperties(propertiesFile ="/home/memin/.config/customMemin/conf.properties", key=''):
    """
    Reads a .properties file and returns the key value pairs as dictionary.
    if key value is specified, then it will return its value alone.
    """
    with open(propertiesFile) as f:
        l = [line.strip().split("=") for line in f.readlines() if not line.startswith('#') and line.strip()]
        d = {key.strip(): value.strip() for key, value in l}

        if key:
            return d[key]
        else:
            return d
于 2018-11-01T14:04:52.573 回答
0

我遵循了 configparser 方法,它对我来说效果很好。创建了一个 PropertyReader 文件并在那里使用配置解析器来准备属性以对应于每个部分。

**使用 Python 2.7

PropertyReader.py 文件的内容:

#!/usr/bin/python
import ConfigParser

class PropertyReader:

def readProperty(self, strSection, strKey):
    config = ConfigParser.RawConfigParser()
    config.read('ConfigFile.properties')
    strValue = config.get(strSection,strKey);
    print "Value captured for "+strKey+" :"+strValue
    return strValue

读取架构文件的内容:

from PropertyReader import *

class ReadSchema:

print PropertyReader().readProperty('source1_section','source_name1')
print PropertyReader().readProperty('source2_section','sn2_sc1_tb')

.properties 文件的内容:

[source1_section]
source_name1:module1
sn1_schema:schema1,schema2,schema3
sn1_sc1_tb:employee,department,location
sn1_sc2_tb:student,college,country

[source2_section]
source_name1:module2
sn2_schema:schema4,schema5,schema6
sn2_sc1_tb:employee,department,location
sn2_sc2_tb:student,college,country
于 2019-02-24T14:25:40.470 回答
0

Lightbend 发布了Typesafe Config库,它解析属性文件和一些基于 JSON 的扩展。Lightbend 的库仅适用于 JVM,但它似乎被广泛采用,现在有多种语言的端口,包括 Python:https ://github.com/chimpler/pyhocon

于 2018-05-01T22:42:50.933 回答
0

这对我有用。

from pyjavaproperties import Properties
p = Properties()
p.load(open('test.properties'))
p.list()
print p
print p.items()
print p['name3']
于 2019-02-12T22:56:42.867 回答