Uncategorized

How to use properties files in python?

Since I come from a Java background, I have been using properties files for most of the dynamic configuration for the projects. Since using properties files for having reusable values makes looks your code clean.

But since I have been trying to learn python, I decided to make my personal project in python this time and count not find much about using properties files.

How to use properties files?

Python has a module named jproperties. It is a Java Property file parser and writer for Python. For installation, we will run this command into the terminal

pip install jproperties

Now lets create our properties file. I have named my property file as config.properties.

Here is how my config.properties looks like

API_ENDPOINT = "[<https://pixe.la/v1>](<https://pixe.la/v1>)"
userEndPoint = "/users"
updateEndPoint = "/graphs"

Now to use this property file we will write a program to read this properties file.

  • Import the module
from jproperties import Properties
  • Load the properties file into our properties object.
configs = Properties()
with open('config.properties', 'rb') as read_prop:
configs.load(read_prop)
  • items method will return a collection of the tuple, Which contains Keys and Corresponding PropertyTuple values
prop_view = configs.items()
for item in prop_view:
    print(item)

Here is what my final code looks like:

from jproperties import Properties

configs = Properties()
with open('config.properties', 'rb') as read_prop:
    configs.load(read_prop)
    
prop_view = configs.items()

for item in prop_view:
    print(item)

print("API Endpoint:",configs.get("API_ENDPOINT").data)

Now let us run the program and see if we could read the properties from the config file.

Here is the output of the program:

Leave a Reply

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