Monday, August 22, 2022

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

Issue

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
# with the specified path 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")


Answered By - Szabolcs
Answer Checked By - David Goodson (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.