How to Upload a File to Google Colab (txt, csv, json, xml, xlsx)


Google Colab is the most widely used Python Notebook to quickly test your Python code snippets, if you have a use case where you want to upload a certain file say .csv, .json, or .txt, and wondering how to upload it so you can use it, then you can make use of files from google.colab module,

Example:
from google.colab import files
uploaded = files.upload()

Choose File: sample-json-file.txt
(text/plain) - 358 bytes, last modified: n/a - 100% done
Saving sample-json-file.txt to sample-json-file.txt

When you execute this code snippet you will get the option to upload a file,

Upload a file to Google Colab - Python Notebook
Upload a file to Google Colab - Python Notebook

Now you can read the file and use it the way you want in your code!

import json

json_file = open("sample-json-file.txt", "r")

json_str = json_file.read()
json_obj = json.loads(json_str)

for element in json_obj:
  print(element['name'])
  print(element['age'])
  print(element['city'])
  print("-----------")
Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.