[英]How can I specify the exact folder IN STREAMLIT for the uploaded file to be saved to?
我正在嘗試為我的基於方面的情緒分析項目創建一個帶有流光和 python 的簡單 GUI,用戶應該能夠上傳一個 .txt 文件,以便我可以在該文件上運行 model。 我已經創建了用於上傳文件的小部件。 我的問題是:
上傳的文件應該添加到特定的文件夾中,如何指定要保存的上傳文件的確切位置?
uploaded_file = st.file_uploader('FILE UPLOAD')
(這是上傳小部件的代碼)
file_uploader
function 不會將文件保存到磁盤,而是寫入 BytesIO 緩沖區。
UploadedFile class 是 BytesIO 的子類,因此它是“類文件”。 這意味着您可以將它們傳遞到預期文件的任何位置。
https://docs.streamlit.io/en/stable/api.html?highlight=file_uploader#streamlit.file_uploader
如果要將結果保存為文件,請使用標准 Python 文件 io 功能:
with open(filename, "wb") as f:
f.write(buf.getbuffer())
要添加@RandyZwitch 所說的內容,您可以使用此 function 保存到您選擇的目錄(目錄/文件夾“tempDir”)
def save_uploaded_file(uploadedfile):
with open(os.path.join("tempDir",uploadedfile.name),"wb") as f:
f.write(uploadedfile.getbuffer())
return st.success("Saved file :{} in tempDir".format(uploadedfile.name))
並在您上傳的文件下方應用 function,如下所示
datafile = st.file_uploader("Upload CSV",type=['csv'])
if datafile is not None:
file_details = {"FileName":datafile.name,"FileType":datafile.type}
df = pd.read_csv(datafile)
st.dataframe(df)
# Apply Function here
save_uploaded_file(datafile)
您可以像這樣定義路徑:
from pathlib import Path
path = "C:/Projects/ex1/your_file"
file_path = Path(path)
uploaded_file = st.file_uploader(file_path)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.