- Create the 
.envFile - Install the 
python-dotenvLibrary - Use the 
.envFile in Your Code - Include 
.envin.gitignore - To prevent accidentally committing sensitive data like API keys to your version control system, add the 
.envfile to your.gitignorefile. 
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_hereInstall the python-dotenv package to load environment variables from your .env file into your Python script.
pip install python-dotenvImport 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}")Example .gitignore:
.envWhy Not Save Inside .venv?
- Separation of Concerns: 
.venvis exclusively for managing the virtual environment dependencies, not for application configurations. - Portability: If the virtual environment is recreated (e.g., after sharing the project), files stored in 
.venvmay be lost. - Security: Storing sensitive information in 
.venvcan 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.