17

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?

Dylan Riley
  • 409
  • 1
  • 4
  • 14

1 Answers1

41

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"])
Niko Föhr
  • 28,336
  • 10
  • 93
  • 96
jkr
  • 17,119
  • 2
  • 42
  • 68