Friday, January 7, 2022

Save code from Colab to Drive

Save code from Colab to Drive

Save code in Google Colab to Google Drive

Assume that we are working with Python in Google Colab. Now we have an awesome algorithm called demo:

def demo():
    print("Hello the world from demo()") 

Question: How do we save this function to our Drive?

This Notebook can be found on Github.


A simple solution is to use the packages drive, os and the magic syntax %%writefile as follows.

Step 1. Create a folder in Drive

We first mount our drive to Colab.

from google.colab import drive
drive.mount('/content/drive')

A window will pop up and we have to connect our google acount to access the Drive.

Now, import os package to manipulate the files.

import os

Let’s move to our Drive, create a working folder and enter it.

os.cddir("/content/drive/MyDrive")
folder_name = "working"
os.mkdir(folder_name)
os.chdir(folderr_name)

Now, we are inside the folder working. We can check it by using the command os.getcwd().

Step 2. Save the function

Now we put the demo function into a script named learn_1.py and save it to the working folder by using the magic command %%writefile.

%%writefile learn_1.py 

def demo():
    print("Hello the world from demo()") 

Step 3. Reuse the function

In the future, you can re-use this function by doing as follows. Go to Goggle Colab and run the following code.

# go to the folder
from google.colab import drive
drive.mount('/content/drive')
import os
os.cddir("/content/drive/MyDrive/working")# the path of file learn_1.py

# begin your code 
from learn_1.py import demo
demo()

Again, we have connect to our Drive and will get the string "Hello the world from demo()" as desired.

Note. Make sure that we are being in the folder containing learn_1.py, otherwise, we cannot import it. In such case, we may create an empty folder named __init__.py in working folder. This set the whole folder working as a Python package, so you can import demo function by the command from working.learn_1 import demo assuming that we are in the path /content/drive/MyDrive containing working folder.

Popular Posts