How to get env variables from .env file using Python.

Free Python Code - Sep 6 '23 - - Dev Community

Hi 🙂🖐

In this post, I will share with you how o get env variables from .env file using Python.

a dotenv is used to store “environment variables” AKA variables we need to configure our code environment. This can include information like is our project running in “production” mode or “developer” mode but most importantly, API and database keys. These variables are ones we need in order to access our project’s various services but don’t want others to be able to see and access. An example of this would include a discord bot token you created — if it was available to view in your code, anyone would be able to log in as your bot.

To load environment variables from .env file you need to install
python-dotenv from here 🤗
https://pypi.org/project/python-dotenv/

Create .env file and add variables

a = 123
x = 100
Enter fullscreen mode Exit fullscreen mode

Now we have a .env file we can load environment variables
using this code.

import dotenv
import os

dotenv.load_dotenv()

val = os.environ.get('x')
print(val)
Enter fullscreen mode Exit fullscreen mode

result

123
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .