我们可以使用jproperties
模块在Python中读取属性文件。属性文件中每一行都包含键值对。等号(=)作为键和值之间的分隔符。以#开头的行被视为注释。
安装jproperties库
该模块不是标准安装的一部分。我们可以使用PIP安装jproperties模块。
# pip install jproperties
在Python中读取属性文件
I have created a properties file for our example: app-config.properties.
# Database Credentials
DB_HOST=localhost
DB_SCHEMA=Test
DB_User=root
DB_PWD=root@neon
# 数据库 凭据
from jproperties import Properties
configs = Properties()
第一步是将Properties对象导入我们的Python程序并实例化。
with open('app-config.properties', 'rb') as config_file:
configs.load(config_file)
下一步是将属性文件加载到我们的Properties对象中。
推荐阅读: Python with语句
现在,我们可以使用get()
方法或通过索引来读取特定属性。Properties对象非常类似于Python字典。
print(configs.get("DB_User"))
该值存储在PropertyTuple对象中,它是两个值的具有命名的元组 - data和meta。jproperties还支持属性元数据,但我们在这里不关心。
print(f'Database User: {configs.get("DB_User").data}')
# PropertyTuple(data='root', meta={})
print(f'Database Password: {configs["DB_PWD"].data}')
# Database User: root
# Database Password: root@neon
print(f'Properties Count: {len(configs)}')
我们可以使用len()函数来获取属性的计数。
# Properties Count: 4
random_value = configs.get("Random_Key")
print(random_value) 如果键不存在,get()方法将返回None。
# None
try:
random_value = configs["Random_Key"]
print(random_value)
except KeyError as ke:
print(f'{ke}, lookup key was "Random_Key"')
但是,如果我们使用索引,那么将引发KeyError
。在这种情况下,最好使用try-except块来处理此异常。
# 输出:
# ‘Key not found’,查找键为”Random_Key”时未找到
items_view = configs.items()
print(type(items_view))
for item in items_view:
print(item)
我们可以使用items()方法获取一个包含键和相应属性元组的元组集合。
<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={}))
输出:
for item in items_view:
print(item[0], '=', item[1].data)
由于我们想要以key=value的格式输出,我们可以使用以下代码。
DB_HOST = localhost
DB_SCHEMA = Test
DB_User = root
DB_PWD = root@neon
输出:
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’]
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.
db_configs_dict = {}
for item in items_view:
db_configs_dict[item[0]] = item[1].data
print(db_configs_dict)
将Python读取属性文件转换为字典
# {‘DB_HOST’: ‘localhost’, ‘DB_SCHEMA’: ‘Test’, ‘DB_User’: ‘root’, ‘DB_PWD’: ‘root@neon’}
Source:
https://www.digitalocean.com/community/tutorials/python-read-properties-file