File_uploader() rather odd behavior

I was wondering if someone can explain the odd behavior in the file uploader. It fails with following error
TypeError: Expected file path name or file-like object, got <class โ€˜bytesโ€™> type
df: pandas.DataFrame = pandas.read_csv(filepath_or_buffer=upload_file)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Oddly If I change to accept_multiple_files=True, it works fine !.

Python 3.11.8
streamlit 1.32.2
pandas 2.2.0

import streamlit as st
import pandas

uploaded_files = st.file_uploader("Choose a CSV file", accept_multiple_files=False)

for upload_file in uploaded_files:
    df: pandas.DataFrame = pandas.read_csv(
        filepath_or_buffer=upload_file, delimiter=",", header=None
    )

Hi @bgood,

Thanks for sharing this question!

When you set accept_multiple_files to False, the st.file_uploader returns a single file-like object and not a list. You can resolve the error above by reading the file like so without iterating through it:

import streamlit as st
import pandas as pd

uploaded_file = st.file_uploader("Choose a CSV file", accept_multiple_files=False)

if uploaded_file is not None:
    df = pd.read_csv(filepath_or_buffer=uploaded_file)
1 Like

@tonykip Thanks and appreciate the quick responseโ€ฆ And your explanation makes perfect sense.

1 Like

Glad you found it useful.Happy Streamlit-ing!:balloon:

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.