4

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'
Szabolcs
  • 3,990
  • 18
  • 38
Roso Bergman
  • 41
  • 1
  • 5

2 Answers2

7

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")
Szabolcs
  • 3,990
  • 18
  • 38
0

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.

nos codemos
  • 569
  • 1
  • 5
  • 19
  • The question is about setting not loading. – Szabolcs Sep 23 '21 at 12:20
  • The thing is that I want the env file to start as an empty file and I want in the code to add variables to the file, I tried your and added os.environ['ORI'] = '123', but still when I opened my .env file in notepad it was empty. – Roso Bergman Sep 23 '21 at 12:20
  • 1
    https://stackoverflow.com/questions/63837315/change-environment-variables-saved-in-env-file-with-python-and-dotenv sorry for misreading the question – nos codemos Sep 23 '21 at 12:22
  • @RosoBergman Look at my answer for a possible solution for your problem. – Szabolcs Sep 23 '21 at 12:25