Load Environment Variables From .env File using Python

.env

HOST=localhost

python-dotenv library

  1. Install python-dotenv library from the command line:
pip install python-dotenv
  1. Load environment variables from .env file:
import os
from os.path import dirname, abspath
from dotenv import load_dotenv

path = dirname(abspath(__file__)) + '/.env'
load_dotenv(path)

envVar = os.getenv('HOST')

print(envVar)  # localhost

Leave a Comment

Cancel reply

Your email address will not be published.