// Tutorial //

How to Read Properties File in Python?

Published on August 3, 2022
Default avatar
By Pankaj
Developer and author at DigitalOcean.
How to Read Properties File in Python?

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

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.

Installing jproperties Library

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

# pip install jproperties

Reading Properties File in 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

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

from jproperties import Properties

configs = Properties()

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

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

Recommended Reading: 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.

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.

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.

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.

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.

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_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.

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 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.

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


Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Sign up
About the authors
Default avatar
Pankaj

author

Developer and author at DigitalOcean.

Still looking for an answer?

Was this helpful?

this library doesn’t support multiline string value in properties file.

- ishwor