Skip to content

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 Knowledge sparks

Subscribe to get the latest posts sent to your email.

See also  How to open a jupyter notebook in Google Drive/Github using Colab

Leave a Reply

error: Content is protected !!