import module in Google Colab from google drive - python

Viewed 12326

I have a problem with import ipynb file from my google drive. I've tried solutions from: Importing .py files in Google Colab How to import custom modules in google colab?

but does not work for me.

# COLAB
from google.colab import files
from google.colab import drive
# SYS
import sys
# IPYNB
!pip install import-ipynb
import import_ipynb
# UTIL
import importlib.util

I've tried something like this:

drive.mount('/content/drive')
sys.path.append('/content/drive/My Drive/Colab Notebooks/')
import Data_Preparation_Library

Or this:

!cp "/content/drive/My Drive/Colab Notebooks/Data_Preparation_Library.ipynb"
import Data_Preparation_Library

Here is how my gdrive structure looks like:

enter image description here

Thank You for answers in advance

4 Answers

SOURCE

Step 1 Primarily, you must Mount your google drive in google colab: Code to below, your files on your google drive is import files/packages inside a google colab.

# Mount your google drive in google colab
from google.colab import drive
drive.mount('/content/drive')

Step 2 Secondly, insert the directory to your python path using sys:

# Insert the directory
import sys
sys.path.insert(0,’/content/drive/My Drive/ColabNotebooks’)

Step 3 Now, you can be able to import your module or file stuff from that directory.

# Import your module or file
import my_module

Worked version of Elci's solution for me:

# Mount your google drive in google colab
from google.colab import drive
drive.mount('/content/gdrive')

# Insert the directory
import sys
sys.path.insert(0,'/content/gdrive/My Drive/Colab Notebooks')

# Import your module or file
import my_module

Huseyin Elci, I found a solution which worked for me:

drive.mount('/content/drive')
sys.path.append('/content/drive/My Drive/Colab Notebooks/')
!cp -r "/content/drive/My Drive/Colab Notebooks/Data_Preparation_Library.ipynb" '/content/'

But I will try your approach Thank You for answer

import sys    

path_to_module = '/content/gdrive/My Drive/tmp'
sys.path.append(path_to_module)
print(sys.path)
import tmp
Related