Steps to Add and Use the .env File
⚒️

Steps to Add and Use the .env File

  1. Create the .env File
  2. In the root directory of your project (same level as your app.py or main script), create a new file named .env.

    Example content of .env:

    API_KEY = your_api_key_here
  3. Install the python-dotenv Library
  4. Install the python-dotenv package to load environment variables from your .env file into your Python script.

    pip install python-dotenv
  5. Use the .env File in Your Code
  6. Import the dotenv module in your Python code and call load_dotenv() to load variables from .env.

    
    import os
    from dotenv import load_dotenv
    
    # Load environment variables from .env file
    load_dotenv()
    
    # Access the API key
    api_key = os.getenv("API_KEY")
    
    print(f"Your API key is: {api_key}")
  7. Include .env in .gitignore
    • To prevent accidentally committing sensitive data like API keys to your version control system, add the .envfile to your .gitignore file.
    • Example .gitignore:

      .env

Why Not Save Inside .venv?

  1. Separation of Concerns.venv is exclusively for managing the virtual environment dependencies, not for application configurations.
  2. Portability: If the virtual environment is recreated (e.g., after sharing the project), files stored in .venv may be lost.
  3. Security: Storing sensitive information in .venv can accidentally expose it if the environment is shared or backed up.

By keeping your .env file in the root directory and outside .venv, you maintain a cleaner, more manageable, and secure project structure.