Search code examples
python-3.xpandasdataframejupyter-notebookipywidgets

widgets.FileUpload - Read the uploaded CSV


I am using widgets.FileUpload to upload a CSV to jupyter and read it. I am using below yo upload.

input_file = widgets.FileUpload(
    accept='.csv',  # Accepted file extension e.g. '.txt', '.pdf', 'image/*', 'image/*,.pdf'
    multiple=False  # True to accept multiple files upload else False
)

input_file

I have uplaoded the file and when i print print(input_file.value) I can see the data.

But when i read through data = pd.read_csv(input_file.value, encoding = "ISO-8859-1") I see below error

ValueError: Invalid file path or buffer object type: <class 'dict'>

Any pointers please.


Solution

  • input_file.value is normally a tuple of dicts, hence you need to access the actual file data. This is probably under input_file.value[0]['content'] if you have only uploaded one file. Try this:

    import codecs
    uploaded_file = list(input_file.value.values())[0]
    csv_text = codecs.decode(uploaded_file.content)
    data = pd.read_csv(csv_text)
    

    See here for more information: https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20List.html#File-Upload