How to set environment variables in Google Colab

In this post, we'll cover how to view, set, and utilize environment variables in Google Colab from a Jupyter notebook.

1) Mount the drive:

from google.colab import drive

drive.mount('/content/drive')

You should see something like:

2) Create a .env file:

Select "Files" on the left menu and create a new file called ".env" in the directory /content/drive/MyDrive/

Add your environment variables to .env with the following format

ENV_VARIABLE="Some value"

3) Load it using "python-dotenv", for instance to read an environment variable called ENV_VARIABLE do the following:

# Install python-dotenv
!pip install python-dotenv

import os

import dotenv
from google.colab import drive

drive.mount('/content/drive')

dotenv.load_dotenv('/content/drive/MyDrive/.env')

os.environ.get('ENV_VARIABLE')

Notes:

  • In order to mount the drive, you will get an authorization request to grant Google Drive for Desktop access to your Google account
  • Add the .env file to your .gitignore