Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing .py files in Google Colab

People also ask

Can we run .PY files in Google Colab?

Python script files can also be run on Google colab by a very simple trick. This is a very useful trick, as it enables you to make use of the GPU/TPU provided by Colab to run your . py file. First, you have to create a new notebook or open an existing one.


You can save it first, then import it.

from google.colab import files
src = list(files.upload().values())[0]
open('mylib.py','wb').write(src)
import mylib

Update (nov 2018): Now you can upload easily by

  • click at [>] to open the left pane
  • choose file tab
  • click [upload] and choose your [mylib.py]
  • import mylib

Update (oct 2019): If you don't want to upload every time, you can store it in S3 and mount it to Colab, as shown in this gist

Update (apr 2020): Now that you can mount your Google Drive automatically. It is easier to just copy it from Drive than upload it.

  • Store mylib.py in your Drive
  • Open a new Colab
  • Open the (left)side pane, select Files view
  • Click Mount Drive then Connect to Google Drive
  • Copy it by !cp drive/MyDrive/mylib.py .
  • import mylib

In case anyone else is interested to know how to import files/packages from gdrive inside a google colab. The following procedure worked for me:

1) Mount your google drive in google colab:

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

2) Append the directory to your python path using sys:

import sys
sys.path.append('/content/gdrive/mypythondirectory')

Now you should be able to import stuff from that directory!


  1. You can upload local files to google colab by using upload() function in google.colab.files
  2. If you have files on github, then clone the repo using !git clone https://github.com/username/repo_name.git. Then just like in jupyter notebook load it using the magic function %load %load filename.py.

Based on the answer by Korakot Chaovavanich, I created the function below to download all files needed within a Colab instance.

from google.colab import files
def getLocalFiles():
    _files = files.upload()
    if len(_files) >0:
       for k,v in _files.items():
         open(k,'wb').write(v)
getLocalFiles()

You can then use the usual 'import' statement to import your local files in Colab. I hope this helps