Importing .py files in Google Colab

2019-02-08 06:16发布

Is there any way to upload my code in .py files and import them in colab code cells?

The other way I found is to create a local Jupyter notebook then upload it to Colab, is it the only way?

5条回答
Summer. ? 凉城
2楼-- · 2019-02-08 06:33

You can upload those .py files to Google drive and allow Colab to use to them:

!mkdir -p drive
!google-drive-ocamlfuse drive

All your files and folders in root folder will be in drive.

查看更多
一夜七次
3楼-- · 2019-02-08 06:39

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 18): 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
查看更多
Root(大扎)
4楼-- · 2019-02-08 06:39
  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.
查看更多
女痞
5楼-- · 2019-02-08 06:40

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

查看更多
Root(大扎)
6楼-- · 2019-02-08 06:49

Try this way:

I have a package named plant_seedlings. The package is stored in google drive. What I should do is to copy this package in /usr/local/lib/python3.6/dist-packages/.

!cp /content/drive/ai/plant_seedlings.tar.gz /usr/local/lib/python3.6/dist-packages/

!cd /usr/local/lib/python3.6/dist-packages/ && tar -xzf plant_seedlings.tar.gz

!cd /content

!python -m plant_seedlings
查看更多
登录 后发表回答