pythonpython-3.xenvironment-variables.envpython-dotenv

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.

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