I am taking uploaded files in a streamlit interface:
import streamlit as st
uploaded_files = st.file_uploader(
label="documents", type="pdf", accept_multiple_files=True
)
In the next step, I need to pass those files to an API (pybis), which sadly only accepts the file name/path as an input, not the BytesIO object. file.name is a property of the custom bytesIO object which is used, which gives the file name as string. This currently looks like this (and works):
import os
import shutil
with open(file.name, "wb") as out_file:
shutil.copyfileobj(file, out_file)
dataset_new = openbis_object.new_dataset(
files=[file.name]
)
dataset_new.save()
if os.path.isfile(file.name):
os.remove(file.name)
As you see, my workaround is to save the file on the disk, pass the path to the API and then remove the file again. I was wondering, is there a better way of doing this? I'd like to somehow create a temporary file of which I pass the path, instead of doing this.
You can use a dedicated python library to create temporary files.
The creation of temporary files is perfectly normal, that's why dedicated paths in operating systems have been created for this, where files appear and disappear, serving as partial information buffers.
Hence, use the tempfile
library, which has dedicated properties along with the entire path relative to the temporary source, or the file name itself, saving data in a binary or text way.