2 ways to upload a csv file to a Google Colab Notebook

You have a csv file, but you don’t know how to upload it to a Python notebook.

Simon Prudhomme
2 min readApr 6, 2020

This article will help you get started in data science by letting you upload your file to a Python Notebook in Google Colab.

Google Colab is a cloud service, offered by Google (free), based on Jupyter Notebook. This platform allows you to train Machine Learning models directly in the cloud and all for free.

Some of the advantages of Google Colab include easy installation and sharing of Notebooks between users in real time (like other documents in the G-cloud suite). However, loading a csv file requires writing code. I’m going to show you two ways to load a csv file into Colab as a Pandas DataFrame.

  1. To get started, sign in to your Google Account
  2. Then go to https://colab.research.google.com and click on New Python 3 Notebook.
  3. From there add a code cell and import Pandas as shown below:
import pandas as pd

A. Load data from your local drive

  1. Start by writing the following and run the code cell :
from google.colab import files
data_to_load = files.upload()

2. You will be asked to select a file. Click on “Choose files” then select and download the csv file of your choice. You should see the name of the file displayed after Colab downloads it.

3. Finally, write the following code to import your file into a Pandas DataFrame (make sure the file name matches the name of the downloaded file).

import io
df = pd.read_csv(io.BytesIO(data_to_load['filename.csv']))

B. Load data from your Google Drive

In my opinion, this method is the simpler of the two.

  1. In your Google Drive, create a folder.
  2. Upload your csv file to your Google Drive in the folder you just created.
  3. In your Notebook Colab, write the following code:
from google.colab import drive
drive.mount(‘/content/drive’)

4. This command will take you to a Google authentication step. You should see a screen with Google Drive File Stream wishing to access your Google account. After accepting the conditions, copy the verification code and paste it in the area indicated in your Notebook Colab.

5. Then click on the > icon at the top left of the Colab Notebook and then click on Files. Locate the folder you created previously and locate your csv file. Right click on the file and select Copy Path.

6. Finally, copy the Path as shown below:

path = “copy_path_here”
df_bonus = pd.read_csv(path)

Here is a video with the details of the 2nd method:

--

--

Simon Prudhomme

Experienced data scientist with strong background in data science, statistics, marketing & users research. https://www.linkedin.com/in/sprudhomme/