'I keep getting 'None' when getting enviroment variables

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)


Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1