How to use variables from an environment file Python?

Question:

I have a project that I’m working on in which I need to store sensitive information into an environment file as variables that can later be called in my code. I’m having issues with it working and so I’ve dumbed it down to the simplest test I can think of.

I have create a test.py file and a var.env file within the same directory. They are the only files in this directory.

Here is my test.py that simply tried to print the value

#test.py
import os
from dotenv import load_dotenv

print(os.getenv('PROJECT'))

Here is environment file saved as var.env

#.env test file
PROJECT='newproject1234'

When I run test.py I get a response of "none". I know I’ve gotta be missing something simple here. Any help is appreciated.

Asked By: cypherlock1010

||

Answers:

You need to call load_dotenv first.

#test.py
import os
from dotenv import load_dotenv

load_dotenv('var.env')

print(os.getenv('PROJECT'))
Answered By: chepner