Tutorial

How to Read Properties File in Python?

Published on August 3, 2022
Default avatar

By Pankaj

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

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Pankaj

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
July 16, 2021

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

- ishwor

    Try DigitalOcean for free

    Click below to sign up and get $200 of credit to try our products over 60 days!

    Sign up

    Join the Tech Talk
    Success! Thank you! Please check your email for further details.

    Please complete your information!

    Get our biweekly newsletter

    Sign up for Infrastructure as a Newsletter.

    Hollie's Hub for Good

    Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

    Become a contributor

    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

    Welcome to the developer cloud

    DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

    Learn more
    DigitalOcean Cloud Control Panel