I keep getting 'None' when getting enviroment variables

Question:

I’m trying to keep my token in an enviroment variable, so I created the file .env, and I stored the TOKEN there:

TOKEN=XXX

When I run my .py file, I can’t get the enviroment variable TOKEN, it keeps printing ‘None’.

import os
    
token = os.environ.get("TOKEN")
print(token)
Asked By: s0urce

||

Answers:

What you are trying to do is use a dotenv variable directly using os.environ.
In order to use variables from .env, you need the dotenv library.
Install dotenv library:

pip install dotenv

Then import dotenv like this.

from dotenv import load_dotenv
load_dotenv()  # this will load variables from .env.
Answered By: Shadab

If you have tried the answers mentioned by @Shadab and you’re still getting None while printing the values from env.

Maybe you didn’t created the .env file in the correct file directory.

We meed to create the .env file within project scope, not inside any folders.

Answered By: Aashish