본문 바로가기
파이썬(Python)

[파이썬]Streamlit 활용 - 파일업로드

by 즐거운코딩 2024. 4. 13.
반응형

Streamlit에서 파일을 업로드하여 사용하는 방법에 대해 알아보겠습니다.

 

A. st.file_uploader

    기본적으로 업로드 파일 사이즈는 최대 200MB 입니다.

  

st.file_uploader(label, type=None, accept_multiple_files=False, key=None, help=None, on_change=None, args=None, kwargs=None, *, disabled=False, label_visibility="visible")

     type : 허용되는 파일종류(확장자)를 배열로 지정. 기본은 None 이며 모든 확장자 파일 선택 가능
                예시 ['jpg', 'png']

    accept_multile_files : 여러 개 파일 동시에 업로드 가능. 파일 리스트로 값이 저장

 

import streamlit as st
import pandas as pd
from io import StringIO

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(bytes_data)

    # To convert to a string based IO:
    stringio = StringIO(uploaded_file.getvalue().decode("utf-8"))
    st.write(stringio)

    # To read file as string:
    string_data = stringio.read()
    st.write(string_data)

    # Can be used wherever a "file-like" object is accepted:
    dataframe = pd.read_csv(uploaded_file)
    st.write(dataframe)

 

   [샘플] 엑셀 파일을 업로드하여 데이터프레임으로 값을 저장하기

customer_file = st.file_uploader('#### 청구고객사 엑셀파일을 업로드하세요 ####')
if customer_file is not None:
    customer_raw=pd.read_excel(customer_file)
    with st.expander("청구대상 고객사"):
        st.dataframe(customer_raw)

     파일이 업로드된 이후 실행될 코드는 if 문으로 분기가 되어야 하위 코드가 실행되지 않고 대기상태가 유지됩니다.

 

 

파일 여러개 불러오기

import streamlit as st

uploaded_files = st.file_uploader("Choose a CSV file", accept_multiple_files=True)
for uploaded_file in uploaded_files:
    bytes_data = uploaded_file.read()
    st.write("filename:", uploaded_file.name)
    st.write(bytes_data)

 

streamlit file upload

 

반응형