pythonpython-3.xenvironment-variablesdotenv

How to set environment variables in a local .env file using dotenv in python?


I tried the following code but when I opened my env file it was still empty.

import os
from os.path import join, dirname
from dotenv import load_dotenv
    
dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)
    
os.environ['ORI'] = '123'

Solution

  • You need dotenv.set_key for that, like this:

    import dotenv
    
    dotenv_path = "my-custom-dotenv"
    
    # dotenv.set_key will create a dotenv file in the current working directory
    # with the specified name if non existing, then add the "ORI" variable
    dotenv.set_key(dotenv_path, "ORI", "123")
    # add the IRO variable
    dotenv.set_key(dotenv_path, "IRO", "321")
    # change the ORI variable
    dotenv.set_key(dotenv_path, "ORI", "456")
    # remove the IRO variable
    dotenv.unset_key(dotenv_path, "IRO")