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

Time:09-23

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'

CodePudding user response:

https://github.com/theskumar/python-dotenv

You first create your .env file and write your various variables. For example a .env might look like:

password=SUPERSECRETPASSWORD
username=myusername

and so forth. Then you will load your .env using the load_dotenv() function.

This is an example from some code I have in a project:

import os
import psycopg2 as pg2
from dotenv import load_dotenv

# -------------------------------
# Connection variables
# -------------------------------
dotenv_path = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', '.env')) #travels up a level to find the .env
load_dotenv(dotenv_path)

# -------------------------------
# Connection to database
# -------------------------------
# Server connection
db_url = os.environ.get("DATABASE_URL")
CONN = pg2.connect(db_url, sslmode="require")

Please make sure you add .env to your .gitignore file!!!!

EDIT: NVM I misread the question. I'll leave it in though.

CodePudding user response:

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")
  • Related