How to upload and read csv file in Google Colab


Google Colab is the best Notebook for Python developers and students to work online without doing any setup locally and sharing your notebooks with friends and colleges.

If you are new to working with Colab and wondering "how to upload a .csv file that you want to work with?" Well all you need to do is keep make use of the files module from the google.colab package.

Just create a code cell in a Colab and copy and execute the below code.

from google.colab import files
 
uploaded = files.upload()
Upload a file to Google Colab

Once you execute the cell, you will see a Choose Files option, click on it will let you select and upload files that you can use with Colab.

One the file(s) uploaded you will see logs such as,

data.csv(text/csv) - 31 bytes, last modified: n/a - 100% done

 Saving data.csv to data.csv

You can read the file by simply using the filename without any path in your Python code.


Example:
import csv

def read_from_csv_file(data_file):
    with open(data_file, 'r') as file:
        csv_reader = csv.reader(file)
        for row in csv_reader:
            print(row)

csv_file = 'data.csv'

read_from_csv_file(csv_file)
Output:

['Name', 'Age']
['Sam', '22']
['Alex', '34']
['Mike', '32']


Do add a comment if you found this useful, or if you have any queries. I am happy to help!

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap