What is .env file?

A .env, or environment file, is very similar to the popular .txt file except it can be more useful in various ways. This is especially true for a data scientist. Let’s explore the most common benefits of a .env file.

  1. Privacy and Security: A .env helps hide sensitive information such as important passwords and API keys that need to be kept private.
  2. Version Control: It can be added to a .gitignore file so that it won’t be able to be accessed via a repository.
  3. Accessibility: Web development tools such as React use .env to store passwords.
  4. Compatibility: Many programming languages can read .env through the use of libraries and tools and load the environment variables into the application.
  5. Separation of Configuration: Storing configuration settings in a separate .env file keeps them separate from your codebase.

Using .env example:

We can use the dotenv library to use a .env file that we created with Python programming. To do so, we can install the dotenv library into our virtual environment with “pip install python-dotenv”.

Now let’s pretend that we have created a .env file:

MAKE SURE THAT FILE IS IN .GITIGNORE

username = abcde
password = 12345

Now let’s use it with Python

from dotenv import load_dotenv
import os as os
load_dotenv(".env") # Looks for a .env file titled as ".env"

username = os.environ["username"]
password = os.environ["password"]

print(f"Username: {username}")
print(f"Password: {password}")

Output:

Username: abcde
Password: 12345

Therefore we are able to retrieve and use our own secret information by accessing our .env file using Python. Once the .env is ignored using .gitignore, only the local user has access to their own credentials.