Streamlit is a powerful Python library for creating interactive web applications with minimal effort. One of its most useful features is the ability to handle file uploads, allowing users to interact with your application by providing their own data. In this guide, we'll explore how to implement file uploads and process various file types in Streamlit.
Let's start with the simplest form of file upload in Streamlit:
import streamlit as st uploaded_file = st.file_uploader("Choose a file") if uploaded_file is not None: # To read file as bytes: bytes_data = uploaded_file.getvalue() st.write(f"Filename: {uploaded_file.name}") st.write(f"File size: {len(bytes_data)} bytes")
This code creates a file uploader widget and displays basic information about the uploaded file. The file_uploader
function returns None
if no file is uploaded, so we check for this before processing.
Streamlit can handle various file types. Let's look at how to process some common ones:
import pandas as pd uploaded_file = st.file_uploader("Choose a CSV file", type="csv") if uploaded_file is not None: df = pd.read_csv(uploaded_file) st.write(df)
This code reads a CSV file into a pandas DataFrame and displays it.
from PIL import Image uploaded_file = st.file_uploader("Choose an image file", type=["png", "jpg", "jpeg"]) if uploaded_file is not None: image = Image.open(uploaded_file) st.image(image, caption="Uploaded Image", use_column_width=True)
This snippet allows users to upload image files and displays them in the app.
Streamlit also supports multiple file uploads:
uploaded_files = st.file_uploader("Choose files", accept_multiple_files=True) for uploaded_file in uploaded_files: bytes_data = uploaded_file.read() st.write(f"Filename: {uploaded_file.name}") st.write(f"File size: {len(bytes_data)} bytes")
This code allows users to upload multiple files and displays information about each one.
Let's create a simple text analysis tool that processes uploaded text files:
import streamlit as st import nltk from nltk.tokenize import word_tokenize from nltk.corpus import stopwords nltk.download('punkt') nltk.download('stopwords') def analyze_text(text): words = word_tokenize(text) word_count = len(words) stop_words = set(stopwords.words('english')) filtered_words = [word.lower() for word in words if word.isalnum() and word.lower() not in stop_words] unique_words = len(set(filtered_words)) return word_count, unique_words uploaded_file = st.file_uploader("Choose a text file", type="txt") if uploaded_file is not None: text = uploaded_file.getvalue().decode("utf-8") word_count, unique_words = analyze_text(text) st.write(f"Total words: {word_count}") st.write(f"Unique words: {unique_words}")
This example creates a simple text analysis tool that counts total and unique words in an uploaded text file.
It's important to handle potential errors and provide feedback to users:
import streamlit as st import pandas as pd uploaded_file = st.file_uploader("Choose a CSV file", type="csv") if uploaded_file is not None: try: df = pd.read_csv(uploaded_file) st.success("File successfully uploaded and processed!") st.write(df) except Exception as e: st.error(f"Error: {e}") st.warning("Please make sure you've uploaded a valid CSV file.")
This code provides clear feedback to users about the success or failure of file processing.
You can customize the file uploader widget to improve user experience:
st.file_uploader("Choose a file", type=["csv", "txt"], help="Upload a CSV or TXT file", key="file_uploader")
The help
parameter adds a tooltip, while key
allows you to reference this specific widget elsewhere in your code.
File handling in Streamlit opens up a world of possibilities for interactive data processing applications. By mastering these techniques, you can create powerful tools that allow users to work with their own data in your Streamlit apps.
08/11/2024 | Python
08/11/2024 | Python
06/10/2024 | Python
15/11/2024 | Python
06/10/2024 | Python
05/10/2024 | Python
15/11/2024 | Python
15/11/2024 | Python
25/09/2024 | Python
05/11/2024 | Python
15/10/2024 | Python
26/10/2024 | Python