Suppose, you already have some Python code developed that is stored in your Google Drive. Now, you will like to load this code in Colab for further modifications. In this chapter, we will see how to load and run the code stored in your Google Drive.
Tools / Command palette
You will see the list of commands as shown in this screenshot −
Type a few letters like “m” in the search box to locate the mount command. Select Mount Drive command from the list. The following code would be inserted in your Code cell.
# Run this cell to mount your Google Drive. from google.colab import drive drive.mount('/content/drive')
If you run this code, you will be asked to enter the authentication code. The corresponding screen looks as shown below −
Open the above URL in your browser. You will be asked to login to your Google account. Now, you will see the following screen −
If you grant the permissions, you will receive your code as follows −
Cut-n-paste this code in the Code cell and hit ENTER. After a while, the drive will be mounted as seen in the screenshot below −
Now, you are ready to use the contents of your drive in Colab.
You can list the contents of the drive using the ls command as follows −
!ls "/content/drive/My Drive/Colab Notebooks"
This command will list the contents of your Colab Notebooks folder. The sample output of my drive contents are shown here −
Greeting.ipynb hello.py LogisticRegressionCensusData.ipynb LogisticRegressionDigitalOcean.ipynb MyFirstColabNotebook.ipynb SamplePlot.ipynb
Now, let us say that you want to run a Python file called hello.py stored in your Google Drive. Type the following command in the Code cell −
!python3 "/content/drive/My Drive/Colab Notebooks/hello.py"
The contents of hello.py are given here for your reference −
print("Welcome to TutorialsPoint!")
You will now see the following output −
Welcome to TutorialsPoint!
Besides the text output, Colab also supports the graphical outputs. We will see this in the next chapter.