Search code examples
pythonpython-3.xcsvtablib

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


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?


Solution

  • 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)