How to Read Properties File in Python? With Examples

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.

Reading Properties File in Python

I have created a properties file for our example:

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

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

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.

We can use len() function to get the count of properties.

What if the key doesn’t exist?

If the key doesn’t exist, the get() method will return 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.

Printing All the Properties

We can use the items() method to get a collection of Tuple, which contains keys and corresponding PropertyTuple values.


Since we are looking to print key=value as the output, we can use the following code.


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.

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.

Reference: PyPI jproperties page

By admin

Leave a Reply

%d bloggers like this: