Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Environment Variables Saved In .env File With Python and dotenv

I am trying to update .env environment variables with python. With os.environ I am able to view and change local environment variables, but I want to change the .env file. Using python-dotenv I can load .env entries into local environment variables

.env File

key=value

test.py

from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())

print(os.environ['key']) # outputs 'value'

os.environ['key'] = "newvalue"

print(os.environ['key']) # outputs 'newvalue'

.env File

key=value

The .env File is not changed! Only the local env variable is changed. I could not find any documentation on how to update the .env file. Does anyone know a solution?

like image 776
Dylan Riley Avatar asked Sep 10 '20 20:09

Dylan Riley


People also ask

How do you access .env variables in Python?

Read Environment Variables in Python: The os module will require to import to read the environment variables. The os. environ object is used in Python to access the environment variable. The coder can set and get the value of any environment variable by using this object.

How do I get data from .env file in Python?

The load_dotenv method from dotenv provides the functionality to read data from a . env file. You do not need to install the os package as it's built into Python.

Can I use variables in .env file?

You can set default values for environment variables using a .env file, which Compose automatically looks for in project directory (parent folder of your Compose file). Values set in the shell environment override those set in the .env file.


1 Answers

Use dotenv.set_key.

import dotenv

dotenv_file = dotenv.find_dotenv()
dotenv.load_dotenv(dotenv_file)

print(os.environ["key"])  # outputs "value"
os.environ["key"] = "newvalue"
print(os.environ['key'])  # outputs 'newvalue'

# Write changes to .env file.
dotenv.set_key(dotenv_file, "key", os.environ["key"])
like image 191
jakub Avatar answered Oct 30 '22 14:10

jakub