st.file_uploader returns a file-like object, or None until someone picks a file, and you can pass that object straight to pd.read_csv. This post builds a small dashboard on top of it that works with any CSV that has at least one numeric column. It targets Streamlit 1.67.
Quick Example
First make a CSV to test with. This writes 90 days of simulated gym class attendance:
import numpy as np
import pandas as pd
rng = np.random.default_rng(44)
classes = {"Yoga": 18, "Spin": 14, "Strength": 11}
rows = [
{"date": day.date(), "class": name, "attendees": int(rng.poisson(base * (1.3 if day.dayofweek < 5 else 0.8)))}
for day in pd.date_range("2026-04-01", periods=90)
for name, base in classes.items()
]
visits = pd.DataFrame(rows)
visits["revenue"] = visits["attendees"] * 12
visits.to_csv("gym_visits.csv", index=False)
Then save this as app.py, run streamlit run app.py, and upload gym_visits.csv:
from io import BytesIO
import pandas as pd
import streamlit as st
PALETTE = ["#0b7285", "#e8590c", "#5f3dc4", "#2b8a3e", "#c2255c"]
@st.cache_data
def load_csv(data):
df = pd.read_csv(BytesIO(data))
for col in df.select_dtypes(exclude="number"):
dates = pd.to_datetime(df[col], format="ISO8601", errors="coerce")
if dates.notna().all():
df[col] = dates
return df
st.title("CSV Dashboard")
uploaded = st.file_uploader("Upload a CSV file", type="csv")
if uploaded is None:
st.info("Upload a file to see its charts.")
st.stop()
try:
df = load_csv(uploaded.getvalue())
except (pd.errors.EmptyDataError, pd.errors.ParserError, UnicodeDecodeError) as error:
st.error(f"Couldn't read that file: {error}")
st.stop()
numeric = df.select_dtypes("number").columns.tolist()
if df.empty or not numeric or len(df.columns) < 2:
st.error("The file needs data rows, a numeric column and at least one other column.")
st.stop()
first, second, third = st.columns(3)
y = first.selectbox("Value to plot", numeric)
x = second.selectbox("X-axis", [c for c in df.columns if c != y])
groups = [c for c in df.select_dtypes(exclude=["number", "datetime"]) if c != x and df[c].nunique() <= 10]
group = third.selectbox("Split by", groups, index=None, placeholder="Nothing")
how = st.segmented_control("Combine rows with", ["sum", "mean", "max"], default="sum", required=True)
if group:
table = df.groupby([x, group])[y].agg(how).unstack()
else:
table = df.groupby(x)[y].agg(how).to_frame()
colors = [PALETTE[i % len(PALETTE)] for i in range(table.shape[1])]
chart = st.line_chart if pd.api.types.is_datetime64_any_dtype(df[x]) else st.bar_chart
chart(table, color=colors, x_label=x, y_label=f"{how} of {y}")
st.caption(f"{len(df):,} rows and {len(df.columns)} columns in {uploaded.name}")
st.dataframe(df.head(100), hide_index=True, height=250)

With the default choices, the app adds up attendees across the three classes for each date and draws a line chart. Changing Split by to class draws one line per class, and picking class as the x-axis switches to a bar chart:

How Do I Read an Uploaded File in Streamlit?
The object you get back behaves like an open binary file, with two extra attributes you'll use often, name and size:
| To get | Use |
|---|---|
| A DataFrame from CSV | pd.read_csv(uploaded) |
| The raw bytes | uploaded.getvalue() |
| Text | uploaded.getvalue().decode("utf-8") |
| An image | st.image(uploaded) |
| A JSON object | json.load(uploaded) |
Reading the object directly moves its position to the end, so a second pd.read_csv(uploaded) in the same run raises EmptyDataError. Call uploaded.seek(0) first, or work from getvalue() as the app does. Passing the bytes to a @st.cache_data function also means the file is parsed once, not on every widget change.
The file stays in memory on the server. Streamlit doesn't write it to disk for you, so save the bytes yourself if you need to keep them.
Handle Messy CSV Files
Real uploads often use other separators or encodings. sep=None with the Python engine detects the separator, and a second attempt covers files saved as Latin-1:
from io import BytesIO
import pandas as pd
def read_any_csv(data):
for encoding in ("utf-8-sig", "latin-1"):
try:
return pd.read_csv(BytesIO(data), sep=None, engine="python", encoding=encoding)
except UnicodeDecodeError:
continue
print(read_any_csv("city;café visits\nLyon;12\n".encode("latin-1")))
Latin-1 can decode any sequence of bytes, so it never fails, but it can show wrong characters for other encodings.
Accept Excel Files and Multiple Files
Pass a list to type for several formats. With accept_multiple_files=True the widget returns a list, which is empty until something is uploaded. Excel support needs openpyxl installed:
from pathlib import Path
import pandas as pd
import streamlit as st
files = st.file_uploader("Upload reports", type=["csv", "xlsx"], accept_multiple_files=True)
frames = []
for file in files:
reader = pd.read_excel if Path(file.name).suffix.lower() == ".xlsx" else pd.read_csv
frames.append(reader(file).assign(source=file.name))
if frames:
combined = pd.concat(frames, ignore_index=True)
st.dataframe(combined, hide_index=True)
Increase the Upload Size Limit
Files are limited to 200 MB each by default. Set a limit for one widget with max_upload_size, in megabytes, or change the app-wide default in .streamlit/config.toml:
import streamlit as st
st.file_uploader("Large export", type="csv", max_upload_size=500, key="large")
[server]
maxUploadSize = 500
A CSV usually takes more memory as a DataFrame than on disk, so check your host's memory limit before raising this. The deployment post lists the limits for common hosts.
Let Users Download the Result
st.download_button sends data back. Passing a function as data builds the file only when someone clicks, and on_click="ignore" skips the rerun:
import pandas as pd
import streamlit as st
summary = pd.DataFrame({"class": ["Yoga", "Spin"], "attendees": [310, 245]})
st.download_button(
"Download summary",
data=lambda: summary.to_csv(index=False),
file_name="summary.csv",
mime="text/csv",
on_click="ignore",
)
Practical Tips
- Treat uploads as untrusted.
type="csv"filters the file picker, but it doesn't guarantee the contents. Don't unpickle uploaded files. - Check for the columns you need and name the missing ones in the error message.
- Offer a sample file with
st.download_buttonso first-time visitors can try the app.