To be able to parse .env files in Python can be as easy as os.getenv(key). But there are other ways to do it also. In this article, we are going to understand it in some more details along with others ways to do the same.
For this let’s consider that we have an .env file which has the following entries:
// .env
USERNAME=some-username
KEY=some-secret-key
We can get those keys the following ways:
1. Using os.getenv(key)
This is the simplest process and doesn’t require any additional libraries.
import os
print(os.getenv("USERNAME")) # this will print some-username
print(os.getenv("KEY")) # this will print some-secret-key
2. Using open(“.env”)
Can read it as a normal file and then proceed to manually parse the text
with open(".env") as env:
3. Using python-dotenv package
If for some reason, reading the .env file doesn’t work, one can use the python-dotenv package to read the environment files.
You can parse the content like this :
Which would result in (output / stdout) :
Now, if you are using git version control and you never want yourself to push an environment file accidentally then add this to your .gitignore
file and they’ll be conveniently ignored.
from dotenv import load_dotenv
load_dotenv() # take environment variables from .env.
Hopefully this article on how to parse .env files in Python resolves any issue you are having.
Tip: To make sure that the secrets don’t get published to the git repository, add the .env file to .gitignore
// .gitignore
.env
Find more python related items here.