Google Colab: Call a function from another python file

Viewed 4871

I want to run a function DataProcesser from a load_data.py python file, which can be found in my google drive path gdrive/My\ Drive/Colab\ Notebooks/CODEX/source/.

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

# Custom functions/classes
path_to_module = 'gdrive/My\ Drive/Colab\ Notebooks/CODEX/source/'  # Path where all the .py files are, relative to the notebook folder
sys.path.append(path_to_module)
from load_data import DataProcesser

Traceback:

> --------------------------------------------------------------------------- ModuleNotFoundError                       Traceback (most recent call
> last) <ipython-input-30-066e93c75b7d> in <module>()
>      20 path_to_module = 'gdrive/My\ Drive/Colab\ Notebooks/CODEX/source/'  # Path where all the .py files are, relative
> to the notebook folder
>      21 sys.path.append(path_to_module)
> ---> 22 from load_data import DataProcesser
>      23 from train_utils import even_intervals
>      24 from models import *
> 
> ModuleNotFoundError: No module named 'load_data'
> 
> --------------------------------------------------------------------------- NOTE: If your import is failing due to a missing package, you can
> manually install dependencies using either !pip or !apt.
> 
> To view examples of installing some common dependencies, click the
> "Open Examples" button below.
> -------------------------------------------------------------
1 Answers

You probably don't need to escape the spaces in your string path_to_module but it might be that the path Colab sees is different. If you expand the files tab in Colab you can navigate to the files in Google Drive. Then you can right click on the file or folder you want and do Copy path. You can then paste this into the cell where path_to_module is defined.

Suffice to say, it works for me; but my path (.../tmp) will be different to yours.

from google.colab import drive
drive.mount('/content/gdrive')
import sys    
path_to_module = '/content/gdrive/MyDrive/tmp'
sys.path.append(path_to_module)
from mypy import myfunc

I navigated to the tmp folder and copied the properties which I then pasted into the code.

Related