Read properties file in python

How to read properties file in Python using configparser?

In this tutorial we are going to write Python program that will read the properties files using the configparser library of Python.

How to read properties file in Python using configparser?

How to read properties file in Python using configparser and printing the property value?

In Python we can read the configuration file and then is required when you have to use the properties written in properties file in your program. In this tutorial we are going to make a sample property file and then read the values inside this file using configparser library of Python. The configparser library is a Python library which is used to read the configuration files in Python and you can use this to read the configuration files in your program. For example you can store the database connection details in properties file and then use the configparser to parse and read the database connection credentials.

The main use of properties file in programming is to store the configuration parameters, which can be used by program during runtime. For example you can define the database connection string, host, username and password in the properties file and then use these values to connect to database during program execution. In future if your database parameters are changed then you just have to update the values in the property file while your program will remain unchanged. So, this way programmers are using properties file in their program to save various configurable parameters of the application.

Читайте также:  Абсолютное позиционирование

The configparser library comes with Python 3 and it can be imported in Python program by using the import statement ‘import configparser’. After import this library in your program you can create the instance of the parser library and then use it for parsing the properties file. After reading the properties file you can get the value of your property with the help of get() method. Following example shows you how to read the properties file in Python very easily.

Sample Property file

First of all we will create a sample property file and add the properties. Here is sample example of properties file:

# Database Configuration [db] db_url=jdbc:mysql://localhost:3308/mydb user=root password=mypass

Here is the screen shot of the properties file:

Properties file

Installing configparser

The configparser is python library and you should first install in your python environment. The command to install configparser library is:

Above command will install configparser library in you Python environment. Now we can proceed for developing the program to read properties file using configparser library.

Reading properties file in Python using configparser

First of all you have to import the configparser library in your program and for this you can use following python code:

Then we will be able to use this library to load parse the .properties file. After reading the db.properties we can use the get() method to get the value of property in our Python program.

Here is the complete code to read properties file in Python using the configparser:

 import configparser config = configparser.ConfigParser() config.read('db.properties') db_url=config.get("db", "db_url") user=config.get("db", "user") password=config.get("db", "password") print(db_url) print(user) print(password) 

Here is the screen shot of the python program in IDE:

Read Properites file in Python

You can run this program by following command:

Above program will read the property file and print the values of property db_url, user and password on the console.

Here is the output of the program:

$ python readprop.py jdbc:mysql://localhost:3308/mydb root mypass

This way you will be able to use the configparser in Python to read the properties file.

Check more tutorials at:

Tutorials

  1. Python Tutorials
  2. Installing Anaconda Python on Ubuntu
  3. Python Hello World Example
  4. Python parse arguments
  5. Python Keywords and Identifiers Tutorial
  6. Python Dictionary
  7. Convert dictionary to JSON Python
  8. Read JSON file into Python dictionary
  9. Python Tutorials: Python Keywords, variables and comments
  10. Python variables and data types
  11. Why learn python for data science?
  12. How to make a line graph in Matplotlib?
  13. How to download and install urllib3 in Python?
  14. Python 3.9 Tutorial
  15. Python 3.9 Features
  16. How to read properties file in Python using configparser?
  17. How to convert Python dictionary to JSON?
  18. How to pretty print a JSON file in Python?
  19. Exceptions in Python
  20. Example of Looping in Python
  21. Python ModuleNotFoundError
  22. Download S3 file in Python using Boto3 Python library
  23. How to get yesterday date in Python?
  24. How to install Anaconda Python in Windows 10?
  25. How to use requests in Python?
  26. Python 3.11 Tutorials
  27. Python 3.11 new features
  28. Python 3.11 System Requirements
  29. Introduction to Python

Источник

How to Read Properties File in Python?

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

Reading Properties File in Python

# Database Credentials DB_HOST=localhost DB_SCHEMA=Test DB_User=root DB_PWD=root@neon 
from jproperties import Properties configs = Properties() 
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 
print(f'Properties Count: len(configs)>') # Properties Count: 4 

What if the key doesn’t exist?

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) 
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=>)) 
for item in items_view: print(item[0], '=', item[1].data) 
DB_HOST = localhost DB_SCHEMA = Test DB_User = root DB_PWD = root@neon 

Getting List of Keys from the Properties File

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) # 

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

Источник

Оцените статью