
How to Set Your Kali VPS Timezone to Sydney (or Anywhere)
June 23, 2025
Keep SSH Sessions Alive with Tmux
June 25, 2025How to Use a .env File in Python to Load Environment Variables
If you’re passing secret keys or config values like webhooks into your Python scripts using os.getenv()
, you’re probably doing this manually each time with export
or inline variables. It works… until you forget to set them or switch terminals. Let’s fix that properly using a .env file.
🎯 Why use a .env file?
A .env
file lets you define environment variables in one place, outside your codebase. This keeps sensitive data like API keys or Discord webhooks out of your main script and version control. It’s simple, clean and safe, especially when paired with python-dotenv
.
✅ Step 1: Install python-dotenv
Run this inside your virtual environment:
✅ Step 2: Create a .env
file
Inside your project directory, create a file named .env
with your environment variables:
Then make sure to exclude it from Git if you’re using version control:
This adds .env to the .gitignore file so Git will ignore the .env file and not track it.
✅ Step 3: Load the .env file in your script
At the top of your Python script, load the variables:
This loads environment variables from a .env file into your Python script, so you can access them using os.getenv(). It’s like telling Python: “Go read that .env file and make those variables available in the environment.”
Then you can use your variables as usual:
✅ Run your script
Now just run your Python script as normal. The .env
values will load automatically—no more forgetting to export variables each time.
💡 Bonus Tip: Default fallback
If you want a fallback value or error message when a variable is missing, you can do this:
📦 Wrap-Up
Using a .env
file is the cleanest way to manage config data in Python projects. It’s secure, portable, and won’t leave you stuck wondering why your script crashed because you forgot to set an environment variable. One line to load it, and you’re sorted.
⭐ Ready for a reliable, high-performance VPS at an unbeatable price? We host our own Kali labs on Hostinger: 4 vCPU, NVMe storage, 16 GB RAM and 16 TB bandwidth, backed by 24/7 support and a 30-day money-back guarantee. You’ll save up to 20% when you lock in a 24-month plan. Grab a Hostinger VPS using this referral link and support our content.
👉 Claim your Hostinger VPS (from only US$ 7.99/mo)