From a Colab notebook, I would like to call a python function that I wrote in a separate python file. How do I do that?
Edit: If you would like to import a local module, you'll want to edit your sys.path
to point to that new directory. Here's an example notebook:
https://colab.research.google.com/notebook#fileId=1PtYW0hZit-B9y4PL978kV2ppJJPhjQua
Original reply: Sure, here's an example notebook: https://colab.research.google.com/notebook#fileId=1KBrq8aAiy8vYIIUiTb5UHG9GKOdEMF3n
There are two cells: the first defines a .py
file with a function to be imported.
%%writefile example.py
def f():
print 'This is a function defined in a Python source file.'
The second cell uses execfile
to evaluate that .py
file in the notebook's Python interpreter.
# Bring the file into the local Python environment.
execfile('example.py')
# Call the function defined in the file.
f()
Please, try this function to Import a function from your drive to your colab notebook:
from google.colab import files
import zipfile, io, os
def upload_dir_file(case_f):
# author: yasser mustafa, 21 March 2018
# case_f = 0 for uploading one File or Package(.py) and case_f = 1 for uploading one Zipped Directory
uploaded = files.upload() # to upload a Full Directory, please Zip it first (use WinZip)
for fn in uploaded.keys():
name = fn #.encode('utf-8')
#print('\nfile after encode', name)
#name = io.BytesIO(uploaded[name])
if case_f == 0: # case of uploading 'One File only'
print('\n file name: ', name)
return name
else: # case of uploading a directory and its subdirectories and files
zfile = zipfile.ZipFile(name, 'r') # unzip the directory
zfile.extractall()
for d in zfile.namelist(): # d = directory
print('\n main directory name: ', d)
return d
print('Done!')
Then follow the following two steps: 1- If you have a file called (package_name.py), to upload it to your colab notebook call:
file_name = upload_dir_file(0)
2- Then, import your package:
import package_name
Note: you can use the same function to: 1- uploading file(csv, excel, pdf, ....):
file_name = upload_dir_file(0)
2- uploading Directory and its subdirectories and files:
dir_name = upload_dir_file(1)
Enjoy it!
Bob Smith's answer couldn't be run in the colab. the simplest way is :
exec(open(filename).read())
suitable for all versions. good luck!
© 2022 - 2024 — McMap. All rights reserved.