Reading environment variables from more than one ".env" file in Python

I have environment variables that I need to get from two different files in order to keep user+pw outside of the git repo. I download the sensitive user+pass from another location and add it to .gitignore.

I am using

from os import getenv
from dotenv import load_dotenv
    
    ...
    load_dotenv()
    DB_HOST=getenv('DB_HOST') # from env file 1
    DB_NAME=getenv('DB_NAME') # from env file 1
    DB_USER=getenv('DB_USER') # from env file 2
    DB_PASS=getenv('DB_PASS') # from env file 2

and I have the two ".env" files in the folder of the python script.

env_file.env contains:

DB_HOST=xyz
DB_NAME=abc

env_file_in_gitignore.env which needs to stay out of the git repo but is available by download using an sh script:

DB_USER=me
DB_PASS=eao

How to avoid the error:

TypeError: connect() argument 2 must be str, not None
connect() argument 2 must be str, not None

which is thrown since one of the two files are not used for the .env import?

How can I get environment variables from two different ".env" files, both stored in the working directory?


Solution 1:

You can add file path as an argument in load_dotenv function

from dotenv import load_dotenv
import os

load_dotenv(<file 1 path>)
load_dotenv(<file 2 path>)

Solution 2:

there is a method load env file is load_dotenv you can use as many env file you want using

from dotenv import load_dotenv

load_dotenv('path1')
load_dotenv('path2)
...

for more information read this