How can properties files be read in Python?

To read a properties file in Python, we can utilize the jproperties module. Each line in a properties file consists of key-value pairs, with the equals (=) sign acting as the separator between them. If a line begins with #, it is considered a comment.

Installing the jproperties library

The jproperties module is not included in the default installation. We can install it using PIP.

# pip install jproperties

How to read a properties file in Python.

I have made a properties file specifically for our example, named app-config.properties.

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

The initial action is to bring the Properties object into our Python program and create an instance of it.

from jproperties import Properties

configs = Properties()

Our next move involves loading the properties file into the Properties object.

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

Suggested literature: Understanding the Python with Statement

We have the option to retrieve a specific attribute by utilizing the get() function or by accessing it through the index. The Properties object closely resembles a Python Dictionary.

The PropertyTuple object holds the value and consists of two named tuple values – data and meta. Although jproperties also support properties metadata, it is not relevant to us in this context.

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

One option for native paraphrasing could be:
“To obtain the number of properties, we can utilize the len() function.”

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

What happens if the key is not present?

If the key is not present, the get() function will provide None as the output.

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

However, if we employ the index, a KeyError will be raised. In such a scenario, it is more preferable to handle this exception using a try-except block.

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 of the properties

By utilizing the items() method, we can obtain a Tuple collection that comprises both keys and their corresponding PropertyTuple values.

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

for item in items_view:
    print(item)

Can you provide just one alternative option for the following text in your native language:

Result:

<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={}))

In order to obtain the desired output of key=value, we can implement the following code.

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

Result:

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

Obtaining a collection of key entries from the properties file.

I have a full program that can read the properties file and generate a list containing 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']

How can I translate “Python Read Properties File into Dictionary” into one paraphrased option?

“Converting a properties file into a dictionary using Python”

One option for paraphrasing the given statement natively:
A properties file is identical to a dictionary. Consequently, it is customary to retrieve the contents of the properties file and store them in a dictionary. The procedure remains almost the same as mentioned before, except that the iteration code is modified to incorporate the elements into a 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'}

Source: PyPI jproperties page

Paraphrased: Information can be found on the jproperties page of PyPI.

 

more tutorials

init or Swift initialization in Swift(Opens in a new browser tab)

How can I include new entries in a Python dictionary?(Opens in a new browser tab)

get pandas DataFrame from an API endpoint that lacks order?(Opens in a new browser tab)

sudo for new user with privileges on Rocky Linux 8(Opens in a new browser tab)

How to include items to a list in Python(Opens in a new browser tab)

 

 

 

Leave a Reply 0

Your email address will not be published. Required fields are marked *