Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Read Environment Variables with Python dotenv
Next article icon

Read Environment Variables with Python dotenv

Last Updated : 05 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Environment variables play a crucial role in the configuration and operation of software applications. They provide a mechanism to store configuration settings that can be used by applications to function properly. This separation of configuration from code allows for more secure and flexible software development practices.

Introduction to python-dotenv

python-dotenv is a Python package that automates the process of loading environment variables from a .env file into the environment. A .env file is a simple text file that contains key-value pairs representing environment variables. By using python-dotenv, you can easily manage and load these variables in your Python applications without manually setting them in your operating system. With python-dotenv, you can load these variables into your application with just a few lines of code, simplifying configuration management and enhancing security.

A .env file is a simple text file used to store environment variables in a key-value pair format. This file is typically placed in the root directory of your project. The .env file allows you to manage your application's configuration settings in a centralized and organized manner.

Example Project Structure

my_project/
│
├── .env
├── my_script.py
└── requirements.txt

Installing python-dotenv

To get started with python-dotenv, you'll need to install it. You can do this using pip:

pip install python-dotenv

Creating a .env File

Create the .env File: Open your project root directory and create a new file named .env.

env2

Add Environment Variables: In the .env file, add your environment variables as key-value pairs. Each pair should be on a new line. The format is KEY=VALUE.

Here’s an example of a .env file containing:

  • DATABASE_URL stores the connection string for a PostgreSQL database.
  • SECRET_KEY is used for cryptographic operations such as signing cookies or tokens.
  • DEBUG is a flag to indicate whether the application should run in debug mode.
# .env
DATABASE_URL=postgres://user:password@localhost/dbname
SECRET_KEY=your_secret_key
DEBUG=True

Important Considerations

Security: The .env file often contains sensitive information such as API keys, database credentials, and other secrets. It is crucial to ensure that this file is not exposed publicly.

.gitignore: To prevent the .env file from being committed to your version control system (e.g., Git), add it to your .gitignore file. This ensures that sensitive information is not shared inadvertently. Add the following line to your .gitignore file:

Consistency Across Environments: Maintain separate .env files for different environments (e.g., .env.development, .env.testing, .env.production). This allows you to have different configurations for different stages of your application lifecycle without modifying the source code.

env3
example of adding different .env file for different environments

Example .env Files for Different Environments

env4
.env file for development environment

By keeping environment-specific configurations separate, you can easily switch between environments without altering your codebase.

Loading .env Files with python-dotenv

Once you have created and configured your .env file, you can use python-dotenv to load these environment variables into your Python application. This simplifies the process of managing configuration settings and ensures that your application can access the necessary variables.

Reading Environment Variables

Once you have set up your .env file with the necessary environment variables, the next step is to read these variables into your Python application. The python-dotenv package makes this process straightforward.

Step 1. Install python-dotenv

First, you need to install the python-dotenv package if you haven't already. You can do this using pip.

pip install python-dotenv

Step 2. Import and Load the .env File

In your Python script, import the load_dotenv function from the dotenv module and call it to load the environment variables from the .env file.

Python
from dotenv import load_dotenv import os  # Load environment variables from .env file load_dotenv()   

Step 3. Read Environment Variables

Use the os.getenv() function to read the environment variables. This function takes the name of the environment variable as an argument and returns its value.

Python
database_url = os.getenv('DATABASE_URL') secret_key = os.getenv('SECRET_KEY') debug = os.getenv('DEBUG') 

Step 4. Provide Default Values( Optional )

It’s a good practice to provide default values in case an environment variable is not set. This can prevent your application from crashing due to missing environment variables.

Python
database_url = os.getenv('DATABASE_URL', 'default_database_url') secret_key = os.getenv('SECRET_KEY', 'default_secret_key') debug = os.getenv('DEBUG', 'False') 

Step 5. Using the Environment Variables

You can now use these variables in your application as needed. For instance, you can configure your database connection, set up your application’s secret key, or enable/disable debug mode based on these variables.

Python
from sqlalchemy import create_engine  # Use the DATABASE_URL to create a database engine engine = create_engine(database_url)  # Print the values to verify print(f"Database URL: {database_url}") print(f"Secret Key: {secret_key}") print(f"Debug Mode: {debug}") 



Next Article
Read Environment Variables with Python dotenv

S

shalini_chabarwal
Improve
Article Tags :
  • Python
  • Environment
Practice Tags :
  • python

Similar Reads

    Environment Variables in Python
    Environment variables are key-value pairs that live in our system's environment. Python reads some of these variables at startup to determine how to behave, for example, where to look for modules or whether to enter interactive mode.If there’s ever a conflict between an environment variable and a co
    3 min read
    Access environment variable values in Python
    An environment variable is a variable that is created by the Operating System. Environment variables are created in the form of Key-Value pairs. To Access environment variables in Python's we can use the OS module which provides a property called environ that contains environment variables in key-va
    3 min read
    How to Read Environment Variables in Scala?
    Scala stands for scalable language. It is an object-oriented language that provides support for functional programming approach as well. Everything in scala is an object e.g. - values like 1,2 can invoke functions like toString(). Scala is a statically typed language although unlike other statically
    3 min read
    Environment Variables in Java
    In Java, Environment variables are widely used by operating systems to deliver configuration data to applications. Environment variables are key/value pairs with both the key and the value being strings, similar to properties in the Java platform. What are Environment Variables in Java?In Java, Envi
    5 min read
    Convert String into Variable Name in Python
    There may be situations where you want to convert a string into a variable name dynamically. In this article, we'll explore how to convert a string into a variable name in Python with four simple examples. Convert String into Variable Name in PythonWhile Python does not directly allow you to convert
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences