我们可以使用jproperties
模块在Python中读取属性文件。一个属性文件包含每个行中的关键值对。
安装 jproperties 图书馆
我们可以使用 PIP来安装 jproperties 模块。
1# pip install jproperties
在Python中阅读属性文件
我为我们的示例创建了一个属性文件: app-config.properties。
1# Database Credentials
2DB_HOST=localhost
3DB_SCHEMA=Test
4DB_User=root
5DB_PWD=root@neon
第一步是将 Properties 对象导入我们的 Python 程序并实例化。
1from jproperties import Properties
2
3configs = Properties()
下一步是将属性文件加载到我们的属性对象中。
1with open('app-config.properties', 'rb') as config_file:
2 configs.load(config_file)
推荐阅读: [Python with Statement]( / 社区 / 教程 / Python-with-statement-with-open-file)
现在,我们可以使用 `get() 方法或通过索引读取特定属性。 属性对象非常类似于 Python 字典。
该值存储在 PropertyTuple 对象中,该对象名为 tuple的两个值 - data和 meta。
1print(configs.get("DB_User"))
2# PropertyTuple(data='root', meta={})
3
4print(f'Database User: {configs.get("DB_User").data}')
5# Database User: root
6
7print(f'Database Password: {configs["DB_PWD"].data}')
8# Database Password: root@neon
我们可以使用 len() 函数来获取属性的计数。
1print(f'Properties Count: {len(configs)}')
2# Properties Count: 4
如果钥匙不存在怎么办?
如果密钥不存在,则 get() 方法将返回 None。
1random_value = configs.get("Random_Key")
2print(random_value) # None
但是,如果我们使用索引,那么KeyError
就会被提出来,在这种情况下,最好使用 try-except块来处理此例外。
1try:
2 random_value = configs["Random_Key"]
3 print(random_value)
4except KeyError as ke:
5 print(f'{ke}, lookup key was "Random_Key"')
6
7# Output:
8# 'Key not found', lookup key was "Random_Key"
打印所有财产
我们可以使用 items() 方法获得 Tuple 的 收藏,其中包含密钥和相应的 PropertyTuple 值。
1items_view = configs.items()
2print(type(items_view))
3
4for item in items_view:
5 print(item)
出发点:
1<class 'collections.abc.ItemsView'>
2('DB_HOST', PropertyTuple(data='localhost', meta={}))
3('DB_SCHEMA', PropertyTuple(data='Test', meta={}))
4('DB_User', PropertyTuple(data='root', meta={}))
5('DB_PWD', PropertyTuple(data='root@neon', meta={}))
由于我们要将 key=value 打印为输出,我们可以使用以下代码。
1for item in items_view:
2 print(item[0], '=', item[1].data)
出发点:
1DB_HOST = localhost
2DB_SCHEMA = Test
3DB_User = root
4DB_PWD = root@neon
从属性文件中获取密钥列表
这里有一个完整的程序来读取属性文件,并创建所有密钥的 [列表]( / 社区 / 教程 / Python - 列表)。
1from jproperties import Properties
2
3configs = Properties()
4
5with open('app-config.properties', 'rb') as config_file:
6 configs.load(config_file)
7
8items_view = configs.items()
9list_keys = []
10
11for item in items_view:
12 list_keys.append(item[0])
13
14print(list_keys)
15# ['DB_HOST', 'DB_SCHEMA', 'DB_User', 'DB_PWD']
Python 阅读属性文件到字典
属性文件与字典相同,因此,在字典中读取属性文件是一种常见的做法。步骤类似于上面的步骤,但在迭代代码中更改为 添加元素到字典。
1db_configs_dict = {}
2
3for item in items_view:
4 db_configs_dict[item[0]] = item[1].data
5
6print(db_configs_dict)
7# {'DB_HOST': 'localhost', 'DB_SCHEMA': 'Test', 'DB_User': 'root', 'DB_PWD': 'root@neon'}
** 参考**: PyPI jproperties 页面