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.
1 |
# pip install jproperties |
Reading Properties File in Python
I have created a properties file for our example: app-config.properties.
1 2 3 4 5 |
# 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.
1 2 3 |
from jproperties import Properties configs = Properties() |
The next step is to load the properties file into our Properties object.
1 2 |
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.
1 2 3 4 5 6 7 8 |
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: [email protected] |
We can use len() function to get the count of properties.
1 2 |
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.
1 2 |
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.
1 2 3 4 5 6 7 8 |
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.
1 2 3 4 5 |
items_view = configs.items() print(type(items_view)) for item in items_view: print(item) |
Output:
1 2 3 4 5 6 |
<span style="color: #003300;"><strong><class 'collections.abc.ItemsView'> ('DB_HOST', PropertyTuple(data="localhost", meta={})) ('DB_SCHEMA', PropertyTuple(data="Test", meta={})) ('DB_User', PropertyTuple(data="root", meta={})) </strong></span> |
Since we are looking to print key=value as the output, we can use the following code.
1 2 |
for item in items_view: print(item[0], '=', item[1].data) |
Output:
1 2 3 4 5 |
<span style="color: #008000;"><strong>DB_HOST = localhost DB_SCHEMA = Test DB_User = root DB_PWD = root@neon </strong></span> |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
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.
1 2 3 4 5 6 7 |
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': '[email protected]'} |
Reference: PyPI jproperties page