close

How to import custom modules in google colab?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to import custom modules in google colab in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to import custom modules in google colab?

  1. How to import custom modules in google colab?

    One additional observation/comment: for some reason there are circumstances where Google Drive is mounted to the Colab /content/gdrive folder as '/MyDrive' with no space and, in some circumstances it is mounted as '/My Drive' with a space.

  2. import custom modules in google colab

    One additional observation/comment: for some reason there are circumstances where Google Drive is mounted to the Colab /content/gdrive folder as '/MyDrive' with no space and, in some circumstances it is mounted as '/My Drive' with a space.

Method 1

If your Python file is in Drive, it’s likely simpler to mount your Drive than to upload the file, e.g.,

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

Mounted at /content/gdrive

I happen to have an existing .py file in Drive.

!ls /content/gdrive/My\ Drive/*.py
>>> /content/gdrive/My Drive/mylib.py

!cat '/content/gdrive/My Drive/mylib.py'

def MyFunction():
    print ('My imported function')

# We'll need to update our path to import from Drive.

import sys
sys.path.append('/content/gdrive/My Drive')

# Now we can import the library and use the function.

import mylib
mylib.MyFunction()

Method 2

One additional observation/comment: for some reason there are circumstances where Google Drive is mounted to the Colab /content/gdrive folder as ‘/MyDrive’ with no space and, in some circumstances it is mounted as ‘/My Drive’ with a space. I always check the Colab folder structure in the frame on the left of the browser window to confirm which I should use. Not sure what is causing the space/no-space difference; maybe sunspot activity?

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read