How to change working directory in Colab

In Google Colab, cd changes the directory only within the current cell. However, Colab resets the working directory when a new cell runs. To make sure the directory change is persistent, try the following:

Method 1: Change Directory and Confirm

import os

os.chdir('/content/drive/MyDrive/my_folder')  # Change to desired directory
print("Current working directory:", os.getcwd())  # Verify change

This ensures the new directory is set before running commands.

Method 2: Mount Google Drive (if accessing files from Drive)

from google.colab import drive
drive.mount('/content/drive')

%cd /content/drive/MyDrive/my_folder  # Change directory

Make sure your folder exists in Google Drive before running this.

Method 3: Use %cd Magic Command

Google Colab supports the %cd command:

%cd /content/drive/MyDrive/my_folder

This is different from !cd, which only changes the directory temporarily.


Discover more from Science Comics

Subscribe to get the latest posts sent to your email.

Leave a Reply

error: Content is protected !!