- Create the
.env
File - Install the
python-dotenv
Library - Use the
.env
File in Your Code - Include
.env
in.gitignore
- To prevent accidentally committing sensitive data like API keys to your version control system, add the
.env
file to your.gitignore
file.
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
Install the python-dotenv
package to load environment variables from your .env
file into your Python script.
pip install python-dotenv
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}")
Example .gitignore
:
.env
Why Not Save Inside .venv
?
- Separation of Concerns:
.venv
is 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
.venv
may be lost. - 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.