Issue in rerunning file_uploader()

i just installed the latest version of streamlit.

And i am facing the issue in uploading a csv file from local machine through file_uploader and converting it into a pandas data frame using pd.read_csv(). be low is my code.
Please suggest what am i missing here

def csv_test_input(df_train):
    """ Function to take File based inputs for Network parameter """
    uploaded_file = st.sidebar.file_uploader("Telecom Network Test-Data", type="csv")

    if uploaded_file is None:
        return None

    text_io = io.TextIOWrapper(uploaded_file)

    inputDF = pd.read_csv(text_io)

    return inputDF

on the first run everythings works fine, but i am getting error on rerun of the app.
Error that i am getting is
ValueError: I/O operation on closed file.
at line text_io = io.TextIOWrapper(uploaded_file)

Can you let me know how to fix this issue.

-Irfan

It looks like you need to reset your buffer with text_io.seek(0) after reading the csv into pandas.

def csv_test_input(df_train):
    """ Function to take File based inputs for Network parameter """
    uploaded_file = st.sidebar.file_uploader("Telecom Network Test-Data", type="csv")

    if uploaded_file is None:
        return None

    text_io = io.TextIOWrapper(uploaded_file)

    inputDF = pd.read_csv(text_io)
    text_io.seek(0)

    return inputDF

Previously we were creating a new buffer for you each time we reran. To optimize, we are returning the same buffer on rerun. Unfortunately, this means that if youโ€™ve already read the buffer, youโ€™ll need to reset after. If you use .getValue() , thereโ€™s no need to seek . Unfortunately for file uploader pandas.read_csv does a read() which will require a buffer reset.

1 Like

this doesnโ€™t solves my problem, it is still giving me the same error message.
.seek(0) will work if file is open, here the erro is saying that I/O file is closed, i.e. uploaded_file is closed.

can you suggest any workarounds ???

or alternate way to read a csv file into panda frame. I am ready to change my code as well.

Thanks in anticipation.

-Regards,
Irfan

def csv_test_input(df_train):
    """ Function to take File based inputs for Network parameter """
    uploaded_file = st.sidebar.file_uploader("Telecom Network Test-Data", type="csv")
    if uploaded_file is None:
        return None

    # st.text ("File is closed ? --> {} ".format(uploaded_file.closed))
    uploaded_file.seek(0)
    inputDF = pd.read_csv(uploaded_file)
    # st.text ("File is closed ? --> {} ".format(uploaded_file.closed))
    return inputDF

Thanks @karriebear, for your suggestion,
I tried to modify my code and it worked for me .

-Regards,
Irfan

1 Like