Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import python files in google colaboratory?

I am trying to run my program on Google Colab; where my code make use of .py files written seprately.

In normal system I have all files inside one folder and it works using import xyz, but when I tried using same folder in Google drive it gives import error.

like image 317
Bhaskar Dhariyal Avatar asked Mar 07 '18 11:03

Bhaskar Dhariyal


People also ask

Can colab run .PY files?

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.


2 Answers

If you have just 2-3 files, you can try the solution I gave in another question here.

Importing .py files in Google Colab

But if you have something like 5-10 files, I would suggest you put your library on github, then !git clone it to Google Colab. Another solution is to zip all you library files, then modify the first solution by unzipping with !unzip mylib.zip

If those library files are not in a folder structure, just a few files in the same folder. You can upload and save them then import them. Upload them with:

def upload_files():
  from google.colab import files
  uploaded = files.upload()
  for k, v in uploaded.items():
    open(k, 'wb').write(v)
  return list(uploaded.keys())
like image 80
korakot Avatar answered Oct 05 '22 16:10

korakot


Now in googlecolab(Nov 18) you can upload your python files easily

  • Navigate to Files (Tab on your left panel)
  • Click on UPLOAD Upload your python folder or .py files
  • Use googlecolab book to access the file.

Please check my screenshot below! enter image description here

like image 30
Praneeth Avatar answered Oct 05 '22 15:10

Praneeth