Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
like image 368
Roso Bergman Avatar asked Sep 19 '25 21:09

Roso Bergman


1 Answers

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")
like image 56
Szabolcs Avatar answered Sep 22 '25 11:09

Szabolcs