How to Mount Google Drive in Google Colab
Google Colab provides temporary storage during a session. Any files stored in the
/content directory will be deleted when the runtime disconnects.
To store datasets, trained models, and results permanently, it is recommended to
mount your Google Drive in Colab.
Mounting Google Drive allows your notebook to access files directly from your Drive and save outputs there so they remain available even after the Colab session ends.
Step 1: Import the Drive Module
First import the Google Colab drive module.
from google.colab import drive
Step 2: Mount Google Drive
Run the following command to mount your Google Drive.
from google.colab import drive
drive.mount('/content/drive')
After running the command:
- A link will appear in the output.
- Click the link and log in to your Google account.
- Copy the authentication code provided.
- Paste the code back into the notebook.
Or, a Google authentication page will appear. Click “Allow” to grant access.
Once authenticated, your Google Drive will be mounted successfully.
Step 3: Access Your Google Drive Files
After mounting, the contents of your Drive will be available at:
/content/drive/MyDrive
You can list files using Python:
!ls /content/drive/MyDrive
Example: Reading an Image from Google Drive
from PIL import Image
image_path = "/content/drive/MyDrive/images/sample.jpg"
img = Image.open(image_path)
img.show()
Example: Saving Files to Google Drive
You can also save outputs such as generated images, trained models, or results directly into Google Drive.
output_path = "/content/drive/MyDrive/results"
import os
os.makedirs(output_path, exist_ok=True)
# Example file save
with open(f"{output_path}/example.txt", "w") as f:
f.write("This file was saved from Google Colab.")
Typical Folder Structure in Google Drive
MyDrive
│
├── datasets
│ └── images
│
├── models
│ └── diffusion_model.pth
│
└── results
└── generated_images
Important Notes
- Files stored in
/contentare temporary and will be deleted after the session ends. - Files saved in
/content/drive/MyDriveremain permanently in Google Drive. - Mounting Drive requires authentication each time a new Colab session starts.
Remounting Google Drive
If the Drive is already mounted and you want to remount it, use:
drive.mount('/content/drive', force_remount=True)
Unmounting Google Drive
To unmount the Drive from the current session:
drive.flush_and_unmount()
Summary
Mounting Google Drive in Google Colab allows you to store datasets, results, and machine learning models safely outside the temporary Colab environment. It is an essential step for most deep learning workflows that require persistent storage.