Google Colaboratory (often referred to simply as “Colab”) is a phenomenal, cloud-based Jupyter notebook environment that provides free access to powerful GPUs. However, a major limitation of Colab is its ephemeral nature; any files you upload directly to the Colab environment are permanently deleted the moment your session disconnects or times out. To train machine learning models on custom datasets or save your output permanently, you must connect (or “mount”) your persistent Google Drive storage directly to your Colab notebook.
The “Mounting” Concept
In Linux environments (which Colab runs on), “mounting” simply means taking a storage drive (in this case, your cloud-based Google Drive) and attaching it to a specific folder within the local file system. Once mounted, the Python code inside your Colab notebook can read and write files to your Google Drive exactly as if they were sitting on a local hard drive.
How to Mount Google Drive Using Python Code
The most reliable way to connect your Drive is by executing a specific snippet of Python code provided by the google.colab library.
- Open your Google Colab notebook.
- Create a new code cell at the very top of your project.
- Paste the following two lines of code into the cell:
from google.colab import drive
drive.mount('/content/drive')- Run the cell (press Shift + Enter or click the play button).
The Authentication Process
When you run the code, Colab will pause and ask for authorization to access your files.
- A pop-up window or a clickable URL will appear in the output of the cell, reading “Permit this notebook to access your Google Drive files?”
- Click Connect to Google Drive.
- A standard Google sign-in window will open. Select the specific Google account that holds the data you want to access.
- Click Allow to grant Colab permission to view and manage the files in your Drive.
How to Access Your Files
Once the cell successfully finishes executing (usually outputting the message Mounted at /content/drive), your Google Drive is now physically connected to the notebook.
You can browse your files visually by clicking the Folder icon on the far left toolbar of the Colab interface. You will see a new folder named drive. Inside that, expand the MyDrive folder to see all your personal files.
Referencing Files in Your Code
To use a file (like a CSV dataset or an image folder) in your Python scripts, you simply provide the absolute file path starting with /content/drive/MyDrive/.
For example, if you have a folder named “Datasets” in the root of your Google Drive containing a file named “sales.csv”, you would load it using Pandas like this:
import pandas as pd
df = pd.read_csv('/content/drive/MyDrive/Datasets/sales.csv')
Any changes you make, or new files you save to this path, will instantly sync back to your permanent Google Drive account.