Help with "name 'df' is not defined" error

Initially, I was getting this error (error:- ValueError: Invalid file path or buffer object type: <class ‘NoneType’>) so I added this bit to my code which resolved the problem:

if uploaded_file is not None:
    df = pd.read_csv(uploaded_file)
    st.write("Data Set")
    st.dataframe(df,3000,500)

But then I got this error which I can’t seem to resolve, I tried making the df variable global and also made a function but neither worked…

This is a snippet of my code:

import streamlit as st
import pandas as pd
from pandas import DataFrame
import matplotlib.pyplot as plt
import plotly.express as px

#configuration
st.set_option('deprecation.showfileUploaderEncoding', False)
st.title("Data Visualisation App")

# Add sidebar
st.sidebar.subheader("Visualisation settings")

# Setup file upload
global df
uploaded_file = st.sidebar.file_uploader(label="Upload your Excel file", type = ['csv','xlsx'])
if uploaded_file is not None:
    df = pd.read_csv(uploaded_file)
    st.write("Data Set")
    st.dataframe(df,3000,500)

if st.checkbox('Show raw data'):
    st.subheader('Raw data')
    st.write(df)

Hey @Vivika_Martini, the error is in feedback_visualisation_app.py file as shown in the image. Can you please add or provide the repo link so that I can review the code?
As per my knowledge, I don’t think so there is any problem with the provided code snippet.

Thanks

Hey @Vivika_Martini ,

Your code is fine, but python/pandas has a problem reading the xslx files. I tried it with a csv file and it’s OK.
You should add a condition and handle depending on whether it’s a csv or xlsx (use pd.read_excel) :slight_smile:

1 Like

Hey @eri3l thank you! I tried that out and when I upload a CSV file the “name ‘df’ is not defined” error goes away. However, if a file isn’t uploaded the error remains. Do you know how to get rid of it?

Thanks,
Vivika

@Vivika_Martini, if you don’t upload a file, st.checkbox is still waiting for it, so it makes sense it’s throwing an error:

if st.checkbox('Show raw data'):
    st.subheader('Raw data')
    st.write(df)

If you only want this checkbox to show if a file has been uploaded, move it underneath the None condition:

if uploaded_file is not None:
1 Like

Hi @eri3l, I tried that but the error seems to occur further on in my code when I actually do stuff with the df…

@eri3l, It seems that the variable isn’t being recognised outside of the if statement even though I made df a global variable…

Hi sorry, I fixed the problem by putting all my code in the

if uploaded_file is not None:

This is probably a very bad solution, but it works

This is actually the correct solution. On each run of a Streamlit app, your app runs top to bottom. On the first run, uploaded_file has a value of None, because the file uploader hasn’t been used yet. By testing for the value of None, you are building in the logic to ensure that a file has already been uploaded.

1 Like