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

Question:

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?

Asked By: Dylan Riley

||

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"])
Answered By: jkr