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 Propertiesconfigs = 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: rootprint(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 Propertiesconfigs = 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].dataprint(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

如何在Python中读取属性文件?相关推荐

  1. 如何在 Python 中读取 .data 文件?

    什么是 .data 文件? 创建.data文件是为了存储信息/数据. 此格式的数据通常以逗号分隔值格式或制表符分隔值格式放置. 除此之外,该文件可以是二进制或文本文件格式.在这种情况下,我们将不得不找 ...

  2. float在python_如何在python中读取.float文件? - python

    Improve this question 我正在处理大脑MRI数据,它是.float数据. 您知道如何在python中使用它吗? 与 with open('[43x25520].float') as ...

  3. python打开文件报错无效序列_如何在python中读取fasta文件?

    我正在尝试读取FASTA文件,然后查找特定的 motif(string)并打印出序列和次数. A FASTA file只是一系列序列(字符串),以标题行开头,标题或新序列的开头是">& ...

  4. python读取大文件的坑_如何在Python中读取大文件的特定部分

    Given a large file (hundreds of MB) how would I use Python to quickly read the content between a spe ...

  5. python读取多行json_如何在Python中读取包含多个JSON对象的JSON文件?

    所以这是在python中读取JSON文件的标准方法 import json from pprint import pprint with open('ig001.json') as data_file ...

  6. 如何在Python中解析YAML文件

    如何在Python中解析YAML文件? #1楼 不依赖C标头的最简单,最纯净的方法是PyYaml( 文档 ): #!/usr/bin/env pythonimport yamlwith open(&q ...

  7. matlab分析xml文件_如何在Java中读取XML文件(DOM分析器)

    matlab分析xml文件 Today we will learn how to read the XML file in Java. We will also learn how to parse ...

  8. 如何在 R 中读取 Zip 文件

    您可以使用以下基本语法将 ZIP 文件读入 R: library(readr)#import data1.csv located within my_data.zip df <- read_cs ...

  9. python读json文件数组_如何在python中从json文件读取json对象数组

    我有一个名为example.json的json文件,包含以下内容[{ "product/productId" : "XXX", "product/ti ...

最新文章

  1. 简单的活又谈何容易呢
  2. bootstrapt学习指南_TensorFlow 2.0深度强化学习指南
  3. 全局路径规划:图搜索算法介绍6(A star)Matlab算法实现
  4. loadrunner之header相关,token等
  5. jquery简单的选择添加下拉列表
  6. 地理加权归回模型 (GWR) 参数估计
  7. 考研经验贴 and 一些感想
  8. 中国多端柔性直流输电行业发展分析及投资可行性调研报告2022-2028年版
  9. SQL Server 数据库安装教程SQL Server 2017
  10. 怎么在图片上编辑文字?图片加字这样做
  11. 12星座的出生年月日性格_十二星座出生日期
  12. Kernel:里的某某某;xxx
  13. ubuntu 17 linux 网络,无路由器的情况下linux(ubuntu 17.04)如何连接联通的校园宽带?...
  14. 小白的jquery学习之路之04效果新闻向上无缝循环显示
  15. 如何调整DOSBox窗口大小
  16. AB test | 学习笔记
  17. c语言设计一个学生成绩管理系统,用C语言设计的学生成绩管理系统1.doc
  18. 企业引入大数据/AI 的难点,落地方式以及行业阶段
  19. saf java_Android SAF实现外置SD卡的写入(JAVA层与JNI层hook)
  20. 迅雷下载软件的工作原理(可耻啊)

热门文章

  1. 数据库:MySQL(单表的表记录的操作)(二)
  2. 韩顺平循序渐进学java 第21.22.23.24讲 集合
  3. 【ArcGIS 10.2新特性】Portal for ArcGIS新特性
  4. [转载] python numpy--矩阵的通用函数
  5. [转载] 【python】定义带参数的装饰器,用装饰器限制函数的参数类型
  6. python进阶之装饰器之5把装饰器作用到类和静态方法上
  7. 代码质量管控的四个阶段
  8. Unreal Engine 4 —— 基于Kajiya-Kay的材质迭代
  9. 老李分享:HTTP协议之协议头
  10. linux centos 系统php支持jpeg的安装方法