PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, August 22, 2022

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

 August 22, 2022     dotenv, environment-variables, python, python-3.x     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing