Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

jupyter notebook - Importing .py files in Google Colab

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...