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

fig : 1 Python : Creating config file
fig : 1 Python : Creating config file

Now we have created a config file

Fig : 2 Python : config file created
Fig : 2 Python : config file created

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

fig : 3 Python : YouTube opened
fig : 3 Python : YouTube opened

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 may also like...

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: