이성령
이성령

Reputation: 1324

How to import .py in google Colaboratory?

I want to simplify code. so i make a utils.py , but Google Colaboratory directory is "/content" I read other questions. but this is not my solution

In Google's Colab notebook, How do I call a function from a Python file?

%%writefile example.py
def f():
 print 'This is a function defined in a Python source file.'
# Bring the file into the local Python environment.
execfile('example.py')
f()
This is a function defined in a Python source file.

It look likes just using def().
using this, i always write the code in cell.

but i want to this code

import example.py
example.f()

Upvotes: 7

Views: 13628

Answers (7)

Mehedee Hassan
Mehedee Hassan

Reputation: 133

STEP 1. I have just created a folder 'common_module' like shown in the image :

enter image description here

STEP 2 called the required Class from my "colab" code cell,

sys.path.append('/content/common_module/')
from DataPreProcessHelper import DataPreProcessHelper as DPPHelper

My class file 'DataPreProcessHelper.py' looks like this

enter image description here

Upvotes: 0

Alhabib
Alhabib

Reputation: 61

Use this if you are out of content folder! hope this help!

import sys
sys.path.insert(0,'/content/my_project')
from example import*

Upvotes: 0

Dmitry
Dmitry

Reputation: 83

import importlib.util
import sys
from google.colab import drive

drive.mount('/content/gdrive')

# To add a directory with your code into a list of directories 
# which will be searched for packages
sys.path.append('/content/gdrive/My Drive/Colab Notebooks')
import example.py

This works for me.

Upvotes: 1

hgzech
hgzech

Reputation: 99

This code should work with Python 3:

from google.colab import drive
import importlib.util
# Mount your drive. It will be at this path: "/content/gdrive/My Drive/"
drive.mount('/content/gdrive')
# Load your module
spec = importlib.util.spec_from_file_location("YOUR_MODULE_NAME", "/content/gdrive/My Drive/utils.py")
your_module_name = importlib.util.module_from_spec(spec)
spec.loader.exec_module(your_module_name)

Upvotes: 0

Mohbat Tharani
Mohbat Tharani

Reputation: 560

Add path of 'sample.py' file to system paths as:

import sys
sys.path.append('drive/codes/') 
import sample

Upvotes: -1

Xuan Shao
Xuan Shao

Reputation: 1

I have also had this problem recently.

I addressed the issue by the following steps, though it's not a perfect solution.

src = list(files.upload().values())[0]
open('util.py','wb').write(src)
import util

Upvotes: 0

zhpger
zhpger

Reputation: 31

A sample maybe you want:

!wget https://raw.githubusercontent.com/tensorflow/models/master/samples/core/get_started/iris_data.py -P local_modules -nc

import sys
sys.path.append('local_modules')

import iris_data
iris_data.load_data()

Upvotes: 3

Related Questions