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
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.
mylib.py
in your DriveFiles
viewMount Drive
then Connect to Google Drive
!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!
%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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With