How to import .py in google Colaboratory?
Asked Answered
M

7

7

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()
Maintenon answered 1/3, 2018 at 11:12 Comment(0)
C
3

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()
Confidante answered 17/4, 2018 at 4:2 Comment(0)
D
1
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.

Dominations answered 2/12, 2018 at 13:50 Comment(0)
H
0

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
Howardhowarth answered 26/3, 2018 at 2:46 Comment(0)
H
0

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)
Halfhardy answered 8/11, 2018 at 13:49 Comment(0)
L
0

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

import sys
sys.path.insert(0,'/content/my_project')
from example import*
Laryngotomy answered 27/7, 2020 at 20:11 Comment(0)
U
0

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

Unrestraint answered 4/9, 2020 at 2:46 Comment(0)
A
-1

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

import sys
sys.path.append('drive/codes/') 
import sample
Ascender answered 18/5, 2018 at 15:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.