How to Importing .py Files in Google Colab

Importing .py Files in Google Colab

Google Colab is a powerful platform for running Python code in the cloud, and it's commonly used for data analysis, machine learning, and more. Sometimes, you may need to import external Python files (.py) into your Colab notebooks to reuse code or access functions defined in those files. Let's explore how to do that.

Step 1: Upload the .py File to Google Colab

To import a .py file into Google Colab, you first need to upload the file to your Colab environment. Here's how:

  1. Click on the "Files" icon in the left sidebar of your Colab notebook.
  2. Click on the "Upload" button and select the .py file from your local system.

Step 2: Mount Google Drive (Optional)

If your .py file is stored in your Google Drive, you can mount your Google Drive to Colab to access it directly. Run the following code cell in your Colab notebook:

from google.colab import drive

Follow the prompted instructions to authenticate and mount your Google Drive.

Step 3: Import the .py File

Once the .py file is uploaded or accessible through Google Drive, you can import it into your Colab notebook just like you would import any other Python module:

import example

Then, you can use the functions or classes defined in the imported module within your Colab notebook.


Suppose you have a file named "" containing the following code:


def greet(name):
    print(f"Hello, {name}!")

To import and use this file in a Google Colab notebook:

  1. Upload the "" file to Colab.
  2. Mount Google Drive if the file is stored there.
  3. Import the file in your Colab notebook and use its functions or classes:
# Importing the .py file
import example

# Using the function defined in the imported module

This will output: Hello, John!

By following these steps, you can easily import .py files into your Google Colab notebooks and leverage external code for your projects.



Contact Form