Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to change the path to the .env file?

I used to have the following project structure:

| *other files.py*
| main.py
| .env

Then, I decided to sort the files into directories. The structure turned out to be as follows:

| src
| ∟ *other files.py*
| | main.py
| | .env

Everything worked before that. After that, when I try to get an environment variable, I get None. If you return .env to the directory above, as it was before, everything works again.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there a way to change the path to the .env file without decouple?

I rescheduled .env the file to another folder and would like to receive a variable, not None.

>Solution :

If you are using python-dotenv, you can manually specify the path to the .env file in your main.py or wherever you’re loading environment variables.

Assuming your new structure looks like this:

src/
├── main.py
├── .env
└── other_files.py

You can load the .env file in your main.py like this:

from dotenv import load_dotenv
import os

# Specify the full path to your .env file in the src directory
env_path = os.path.join(os.path.dirname(__file__), '.env')
load_dotenv(dotenv_path=env_path)

# Now, you can access environment variables as usual
my_var = os.getenv('MY_ENV_VARIABLE')

print(my_var)  # This should not return None if the variable is correctly set in .env

where .env file would have

MY_ENV_VARIABLE=some_value
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading