Creating a tablib Dataset using a URL that points to a .csv file

Question:

I am trying to use the tablib library and create a Dataset from a .csv file. The following works:

import tablib
dataset = tablib.Dataset().load(open('data.csv').read())

However, in some cases, I’d like to load the .csv file from a URL.
Any ideas on how to do that?

Asked By: apiljic

||

Answers:

You wrote

def get_ds(filename):
    return tablib.Dataset().load(open(filename).read())

You want

import os.path
import requests

def get_ds(src):
    if os.path.exists(src):
        txt = open(src).read()
    else:
        req = requests.get(src)
        req.raise_for_status()
        txt = req.text

    return tablib.Dataset().load(txt)
Answered By: J_H
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.