14

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.

Bhaskar Dhariyal
  • 1,343
  • 2
  • 13
  • 31

5 Answers5

12

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

Praneeth
  • 313
  • 4
  • 9
7

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())
korakot
  • 37,818
  • 16
  • 123
  • 144
0

For example you have a module like this

simple.py
def helloworld():
   print("hello")

Click arrow on left panel => Choose File tab => Upload simple.py In notebook code like this

import simple
simple.helloworld()
=> hello
daz
  • 696
  • 10
  • 10
0

Something I've used when I have multiple python scripts and want to automatically import through code is to set it up as a package and clone from the repo.

First set up the scripts in a repo with a setup.py and __init__.py files (obviously).

Then add this to the top of your notebook:

!rm -rf <repo-name>  # in case you need to refresh after pushing changes 
!git clone https://github.com/<user>/<repo-name>.git

Then install the package:

!pip install ./<repo-name>

Now conveniently import functions or whatever:

from <app-name>.<module> import <function>
data_modeler
  • 86
  • 1
  • 6
0

I found this easiest way

    from google.colab import drive
    drive.mount('/content/drive')
    %cd /content/drive/MyDrive/directory-location
ChidanshM
  • 33
  • 3