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?
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.
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.
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.
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"])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With