What’s the Default Google Colab Directory To Store Files?

I just spent 10 minutes looking for the file I had written in my Python script in Google Colab. πŸ˜…

πŸ’‘ Google Colab is a popular platform for data scientists and machine learning enthusiasts. You can write and execute Python code in your browser!

Let’s say you want to write to a file in your Colab Notebook like this: πŸ‘‡

print('hello world', file=open('my_file.txt', 'w'))

Where’s the location of this file after running that cell?

πŸ§‘β€πŸ’» Answer: By default, Google Colab starts in the /content directory. This is the root directory where you can perform various operations, similar to a locally hosted Jupyter Notebook.

However, there may be instances where you need to change the directory, especially when you want to access files from different locations or save your work in a specific folder.

How to Change The Directory in Colab?

To change the directory in Google Colab, you can use the %cd command followed by the path of the directory you want to switch to. For example, if you have a folder named 'MyCoolFolder' in your current directory, you can change to this directory by typing %cd MyCoolFolder in a code cell and running it.

This command changes the current working directory for the notebook environment, not just the subshell running the command.

However, if you want to change the directory from Google Colab into Google Drive, you need to connect to Google Drive first. This is because Google Colab and Google Drive are separate services, and you need to establish a connection between them before you can access files from Google Drive in Google Colab. To do this, you can use the following code:

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

After running this code, you will be asked to authorize the connection by signing in to your Google account and copying the authorization code into the input box in Colab.

Once the connection is established, you can change the directory to a specific folder in your Google Drive by using the %cd command followed by the path of the folder in Google Drive. For example:

%cd /content/drive/MyDrive/YourFolder

By default, the path in Google Colab is the root directory. However, depending on your needs, you can change the path to any other directory. This is useful when working on a project involving multiple files stored in different folders. Changing the path allows you to easily access and manipulate these files without moving them to the same folder.

πŸ’‘ Recommended: How I Built a Back-Link Checker Using ChatGPT and Google Colab