0

In the same folder, I have an .env file and a main.py file.

In .env I have set

TOKEN = 123456

And in main.py I have

import os
print(os.getenv('TOKEN'))

When I run the Python script, I get None in the standard output. What am I doing wrong?

I have looked at all the similar questions but it seems like I'm not missing any steps. I'm using MacOS if that affects anything.

Thanks in advance!

Tr3cky
  • 47
  • 3
  • 5
  • 2
    Python doesn't know anything about `.env` files. How are you trying to load values from that file? – larsks Jan 13 '21 at 00:09
  • @GinoMempin I think dotenv is the way to go. I was following a discord bot making tutorial that involves saving the API key in an .env variable, which can be found [here](https://www.freecodecamp.org/news/create-a-discord-bot-with-python/), and encountered the above issue. Not sure why it worked for the tutorial maker. They used repl.it for the tutorial and I did too, but for some reason mine did not work. Anyways I'm moving ahead with `dotenv`! – Tr3cky Jan 13 '21 at 00:30
  • Because putting key-value pairs in a .env file does not automatically export them as environment variables. And Python's .getenv or .environ only reads from environment variables. As [asked by another user](https://stackoverflow.com/questions/65693810/os-getenvtoken-returns-none-with-token-defined-in-env?noredirect=1#comment116151352_65693810), the tutorial probably does some other steps to load the .env file. – Gino Mempin Jan 13 '21 at 00:35

1 Answers1

2

You need to load your .env file beforehand.

You can do it as follow:

from dotenv import load_dotenv
load_dotenv()

You can find more details in the python-dotenv documentation

Marc Dillar
  • 471
  • 2
  • 9