如何在Python中读取属性文件?

We can use jproperties module to read properties file in Python. A properties file contains key-value pairs in each line. The equals (=) works as the delimiter between the key and value. A line that starts with # is treated as a comment.

我们可以使用jproperties模块在Python中读取属性文件。 属性文件在每一行中包含键/值对。 等于(=)用作键和值之间的分隔符。 以#开头的行被视为注释。

安装jproperties库 (Installing jproperties Library)

This module is not part of the standard installation. We can install jproperties module using PIP.

该模块不是标准安装的一部分。 我们可以使用PIP安装jproperties模块。


# pip install jproperties

在Python中读取属性文件 (Reading Properties File in Python)

I have created a properties file for our example: app-config.properties.

我为示例创建了一个属性文件: app-config.properties


# Database Credentials
DB_HOST=localhost
DB_SCHEMA=Test
DB_User=root
DB_PWD=root@neon

The first step is to import the Properties object into our Python program and instantiate it.

第一步是将Properties对象导入我们的Python程序并实例化。


from jproperties import Properties

configs = Properties()

The next step is to load the properties file into our Properties object.

下一步是将属性文件加载到我们的Properties对象中。


with open('app-config.properties', 'rb') as config_file:
    configs.load(config_file)

Recommended Reading: Python with Statement

推荐读物Python with Statement

Now, we can read a specific property using get() method or through the index. The Properties object is very similar to a Python Dictionary.

现在,我们可以使用get()方法或通过索引读取特定属性。 Properties对象与Python字典非常相似。

The value is stored in a PropertyTuple object, which is a named tuple of two values – data and meta. The jproperties support properties metadata too, but we are not interested in that here.

该值存储在一个PropertyTuple对象,它是一个命名为元组两个值- 数据 。 jproperties也支持属性元数据,但是我们对此不感兴趣。


print(configs.get("DB_User"))  
# PropertyTuple(data='root', meta={})

print(f'Database User: {configs.get("DB_User").data}')  
# Database User: root

print(f'Database Password: {configs["DB_PWD"].data}')  
# Database Password: root@neon

We can use len() function to get the count of properties.

我们可以使用len()函数来获取属性计数。


print(f'Properties Count: {len(configs)}')  
# Properties Count: 4

如果密钥不存在怎么办? (What if the key doesn’t exist?)

If the key doesn’t exist, the get() method will return None.

如果键不存在,则get()方法将返回None。


random_value = configs.get("Random_Key")
print(random_value)  # None

But, if we use the index then KeyError is raised. In that case, it’s better to handle this exception using try-except block.

但是,如果我们使用索引,则会引发KeyError 。 在这种情况下,最好使用try-except块来处理此异常。


try:
    random_value = configs["Random_Key"]
    print(random_value)
except KeyError as ke:
    print(f'{ke}, lookup key was "Random_Key"')

# Output:
# 'Key not found', lookup key was "Random_Key"

打印所有属性 (Printing All the Properties)

We can use the items() method to get a collection of Tuple, which contains keys and corresponding PropertyTuple values.

我们可以使用items()方法获取元组的集合 ,该元组包含键和相应的PropertyTuple值。


items_view = configs.items()
print(type(items_view))

for item in items_view:
    print(item)

Output:

输出


<class 'collections.abc.ItemsView'>
('DB_HOST', PropertyTuple(data='localhost', meta={}))
('DB_SCHEMA', PropertyTuple(data='Test', meta={}))
('DB_User', PropertyTuple(data='root', meta={}))
('DB_PWD', PropertyTuple(data='root@neon', meta={}))

Since we are looking to print key=value as the output, we can use the following code.

由于我们希望将key = value打印为输出,因此可以使用以下代码。


for item in items_view:
    print(item[0], '=', item[1].data)

Output:

输出


DB_HOST = localhost
DB_SCHEMA = Test
DB_User = root
DB_PWD = root@neon

从属性文件中获取键列表 (Getting List of Keys from the Properties File)

Here is a complete program to read the properties file and create a list of all the keys.

这是一个完整的程序,用于读取属性文件并创建所有键的列表


from jproperties import Properties

configs = Properties()

with open('app-config.properties', 'rb') as config_file:
    configs.load(config_file)

items_view = configs.items()
list_keys = []

for item in items_view:
    list_keys.append(item[0])

print(list_keys)  
# ['DB_HOST', 'DB_SCHEMA', 'DB_User', 'DB_PWD']

Python将属性文件读入字典 (Python Read Properties File into Dictionary)

A properties file is the same as a dictionary. So, it’s a common practice to read the properties file into a dictionary. The steps are similar to above, except for the change in the iteration code to add the elements to a dictionary.

属性文件与字典相同。 因此,将属性文件读入字典是一种常见的做法。 除了更改迭代代码以将元素添加到Dictionary之外,这些步骤与上述步骤类似。


db_configs_dict = {}

for item in items_view:
    db_configs_dict[item[0]] = item[1].data

print(db_configs_dict)
# {'DB_HOST': 'localhost', 'DB_SCHEMA': 'Test', 'DB_User': 'root', 'DB_PWD': 'root@neon'}

Reference: PyPI jproperties page

参考PyPI jproperties页面

翻译自: https://www.journaldev.com/39861/python-read-properties-file

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值