Uploaded file error until file uploaded

I have two issues one its expecting the file to be uploaded when the form is opened and get the error

NameError: name ‘df’ is not defined

until i upload the file then the error disappears. thats one issue i cant’t seem to solve.

The other is how can I upload either a csv or excel file and get the program to automatically tell what was uploaded and read the dataframe? I have tried .endswith and .seek(0) but to no avail.

Hi @Paul_Smith, welcome to the community! :wave: :partying_face:

It would help if you could share a code snippet that leads to these errors. It will make it easier for us to debug.

NameError: name ‘df’ is not defined

The above error is likely caused due to how you’ve structured your code. I’m guessing you’re trying to use the DataFrame df before it is created by reading your uploaded file. A possible solution is to:

  1. Use an if statement to check if the file has been uploaded
  2. Read the uploaded file into a Dataframe df within the if block
  3. Perform computations on df within the if block.

The other is how can I upload either a csv or excel file and get the program to automatically tell what was uploaded

st.file_uploader has a type argument that accepts an array of allowed file extensions. In your case, it would be type=['csv', 'xlsx']. You can once again use if/else statements to check the MIME type of the uploaded file and use the corresponding pandas method to create df.

Here’s an example:

Code

import streamlit as st
import pandas as pd

# Allow only .csv and .xlsx files to be uploaded
uploaded_file = st.file_uploader("Upload spreadsheet", type=["csv", "xlsx"])

# Check if file was uploaded
if uploaded_file:
    # Check MIME type of the uploaded file
    if uploaded_file.type == "text/csv":
        df = pd.read_csv(uploaded_file)
    else:
        df = pd.read_excel(uploaded_file)

    # Work with the dataframe
    st.dataframe(df.head())

Output

upload-spreadsheet

Happy Streamlit-ing! :balloon:
Snehan

Thanks for that but managed to solve both problems. the first one i used Try Except which worked and my other issue was just a placement error