Python: How to read config files 📂

Hi all,
Today in this article we are going to discuss about config file and how to read config files in python.
What are config files?
Config files are used to store key value pairs or some configurable information that could be read or accessed in the code and at some point, of time.
- Easy to maintain
- We can change the keys at one place in config file
Getting Started
Creating config file
We can create a config file with the extension .cfg

Now we have created a config file

We will create a section in that we can store any key values
We will create a section called LINKS and in that we will store the YouTube link
# This is the section [LINKS]
# We can create multiple sections
[LINKS]
# Storing links in section [LINKS]
youtubelink = "https://www.youtube.com/"
Reading the config file in Python
# importing webbrowser to open the links
import webbrowser
# Importing configparser
import configparser
# CREATE OBJECT
config_file = configparser.ConfigParser()
# PRINT FILE CONTENT
config_file.read('D:\config.cfg') # We need to give the location where our config file is
links=config_file['LINKS']['youtubelink']
print(links)
------------------------------------------------------------------------
Output
"https://www.youtube.com/"
Now we can read the config files
We can also open YouTube by webbrowser.open("https://www.youtube.com/")
. We will remove the print statement and instead we will put webbrowser.open("https://www.youtube.com/")
# importing webbrowser to open the links
import webbrowser
# Importing configparser
import configparser
# CREATE OBJECT
config_file = configparser.ConfigParser()
# PRINT FILE CONTENT
config_file.read('D:\config.cfg') # We need to give the location where our config file is
#print(config_file)
links=config_file['LINKS']['youtubelink']
#print(links)
# We do not need the print statement
webbrowser.open("https://www.youtube.com/")
Output

Like this we can open any website
We will make more detailed articles on config files in upcoming articles
Thanks for reading 📖
Have a nice day!!
You must be logged in to post a comment.