How to run python scripts on Google Colab

Did you know that you run python scripts in Google Colab?

No? Neither did I.

Just learned from reading a reddit comment.

I’m going to show you how to do so in this blog post. So you use Google’s compute power to its full use.

If I learned about this earlier then many of my projects would make be easier.

If you saved your script in your google drive folder. Then click the mont google drive button. And provide permission.

image001.png

I’m just going to have a simple hello world script:

print('Hello World, This is a Google Colab script')

Uploading locally, you can click the upload to session storage. Should work if you file is not too large.

image003.png

Then you run this statement:

!python '/content/colab_script.py'

With the result:

Hello World, This is a Google Colab script

You can upload to drive using:

from google.colab import files
 
uploaded = files.upload()
 
for fn in uploaded.keys():
  print('User uploaded file "{name}" with length {length} bytes'.format(
      name=fn, length=len(uploaded[fn])))

  

First the file will be saved in session storage then you can move it into your drive folder.

image005.png

NOTE: I don’t know if this is a bug. But uploading your py file via the normal file upload on google drive (not colab). Turns the py file into a gdoc file. Which google colab can’t run. So you one will need to upload your file though google colab. To access your files.

Hopefully you found this useful. Knowing you can run some of your scripts on Google Colab.