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("-----------")

Top Hashtags:

Advertisements

Advertisements




Advertisements