A `.env` file (environment file) is a safe and convenient way to store API keys, tokens, and other [[secrets]] outside your source code. This helps keep sensitive data secure and makes your codebase easier to manage and share. ## create environment file You can create a `.env` file using any text editor. Here's how to do it using [[nano]] from the command line with [[Bash]]. Create and open the file in `nano` with ```bash nano .env ``` Inside the file, add a line like the one below. Replace `<your-api-key>` with your actual key value. Do **not** include spaces around the `=` sign. ```nano OPENAI_API_KEY=<your-api-key> ``` Press `Ctrl+O` to save, then `Enter`, and `Ctrl+X` to exit. Confirm you saved the file correctly with ```bash cat .env ``` Then type `clear` to clear the screen so your key is no longer showing. > [!Danger] > Add the `.env` file to your [[gitignore]] file so that it isn't committed to Git or a GitHub repo! > > ```bash > echo '.env' >> .gitignore > ``` ## access environment file Load the environment file in [[Python]] scripts using the `python-dotenv` package. ```bash uv add python-dotenv ``` ```python from dotenv import load_dotenv import os from pathlib import Path env_path = Path('./secrets/.env') load_dotenv(dotenv_path=env_path) api_key = os.getenv("API_KEY") ``` For simpler projects, store the `.env` file in the project root and load automatically with ```python load_dotenv() ``` See [[secrets]] for alternative methods of accessing passwords, like the library `getpass` which allows a user to type it in for [[command line interface|CLI]] tools.