ProCodebaseProCodebase
  • ModusA Growth OS for your business, on WhatsAppKiosqSell more. Chase less.AI InterviewerAutomated screening & AI-led interviewsXperto AIAI prep companion for candidatesAI Tools HubResume builder, learning paths & more
  • Pre-Vetted DevelopersScreened, scored and ready to interviewAI-Native DevelopersSenior engineers on an hourly basis
  • Services
  • Features
  • AI Coaching
  • Jobs
  • FAQs
Sign inBook a demo
  • Services
  • Features
  • AI Coaching
  • Jobs
  • FAQs
Sign inBook a demo
ProCodebaseProCodebase

ProCodebase Technologies builds AI products for hiring and growth, and ships software for clients as a technical consultancy. We source, screen and deliver pre-vetted developers — so you only interview high-signal candidates.

Products

  • Modus
  • Kiosq
  • AI Interviewer
  • Xperto AI
  • AI Tools Hub

Hire & build

  • Pre-Vetted Developers
  • AI-Native Developers
  • Technical Consultancy
  • MVP Development
  • Features

Resources

  • Articles
  • Topics
  • Certifications
  • Collections
  • Jobs

Company

  • About Us
  • Contact Us
  • Book a Demo
  • FAQs

© 2026 ProCodebase Technologies. All rights reserved.

  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Mastering File Uploads and Handling in Streamlit

author
Generated by
ProCodebase AI

15/11/2024

python

Sign in to read full article

Introduction to File Handling in Streamlit

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.

Basic File Upload

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.

Handling Different File Types

Streamlit can handle various file types. Let's look at how to process some common ones:

CSV Files

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.

Image Files

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.

Multiple File Uploads

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.

Practical Use Case: Text Analysis

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.

Error Handling and User Feedback

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.

Customizing the File Uploader

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.

Conclusion

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.

Popular tags

pythonstreamlitfile-upload

Share now!

Like & bookmark

Related collections

  • PyTorch Mastery: From Basics to Advanced

    14/11/2024 · Python

  • Advanced Python Mastery: Techniques for Experts

    15/01/2025 · Python

  • Mastering Hugging Face Transformers

    14/11/2024 · Python

  • Python with Redis Cache

    08/11/2024 · Python

  • Mastering LangGraph: Stateful, Orchestration Framework

    17/11/2024 · Python

Related articles

  • Mastering Pie Charts and Donut Plots with Matplotlib

    05/10/2024 · Python

  • Unleashing the Power of Class-Based Views and Generic Views in Django

    26/10/2024 · Python

  • Unleashing the Power of Custom Tools and Function Calling in LangChain

    26/10/2024 · Python

  • Mastering Memory Systems and Chat History Management in LangChain with Python

    26/10/2024 · Python

  • Mastering Media Files in Streamlit

    15/11/2024 · Python

  • Building Deep Learning Models with TensorFlow and PyTorch

    15/01/2025 · Python

  • Mastering Pandas Categorical Data

    25/09/2024 · Python

Popular category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design