如何在 STREAMLIT 中指定要保存上传文件的确切文件夹?

How can I specify the exact folder IN STREAMLIT for the uploaded file to be saved to?

我正在尝试使用 streamlit 和 python 为我的基于方面的情绪分析项目创建一个简单的 GUI,用户应该能够上传一个 .txt 文件,这样我就可以 运行该文件上的模型。我已经创建了用于上传文件的小部件。我的问题是:

上传的文件应该添加到特定的文件夹中,如何指定要保存上传文件的确切位置?

uploaded_file = st.file_uploader('FILE UPLOAD')

(这是上传小部件的代码)

您可以这样定义路径:

from pathlib import Path
path = "C:/Projects/ex1/your_file"
file_path = Path(path)

uploaded_file = st.file_uploader(file_path)

file_uploader 函数不会将文件保存到磁盘,它会写入 BytesIO 缓冲区。

The UploadedFile class is a subclass of BytesIO, and therefore it is “file-like”. This means you can pass them anywhere where a file is expected.

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 所说的内容,您可以使用此功能保存到您选择的目录(directory/folder“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))

并在您上传的文件下方应用该功能,如下所示

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)