File uploader

How to use the file uploader in the libraries that need to use the name of the data file and the path of the file to run?
for example :
datafile format: filename.segy
requirement library:segysak.segy
scan = segy_header_scan(“filename.segy”)
in this condition, if I use a file uploader, I resive this error:
FileNotFoundError: [Errno 2] No such file or directory
how can I fix it?
please guide me.
thanks

If the API you want to use only accepts a file path as input, you can use the tempfile (tempfile — Generate temporary files and directories — Python 3.9.13 documentation) module to create a NamedTemporalFile to hold the data from st.file_uploader. Here is an example:

readSGY

import streamlit as st
import tempfile
from segysak.segy import segy_header_scan

## Your uploaded SGY file now exists in memory
uploadedSGY = st.file_uploader("Upload file","SGY")

if uploadedSGY:
    
    ## Creates a temporal file
    with tempfile.NamedTemporaryFile() as tempSGY:
        ## Writes the SGY to the temporal file
        tempSGY.write(uploadedSGY.getbuffer())
        
        ## Now you can use the temporal file path
        scan = segy_header_scan(tempSGY.name)
        
        ## Show the data
        st.dataframe(scan)

Thank you for your guidance
I tried your same codes for my own data file but I got the following error:
PermissionError: [Errno 13] Permission denied
I have created the virtual environment for Streamlit using Anaconda.
This error is not because of the codes, but I don’t know how to fix it. Can you advise on this?

Maybe Anaconda does not have permission to write into the temporal files folder of your system. You could try changing the directory in which the temp file is created, for instance, to put it in the same location of the streamlit script:

with tempfile.NamedTemporaryFile(dir=".") as tempSGY:

(Not recommended but…) If you don’t want to deal with the tempfile module at all, you could write to a regular file:

import streamlit as st
from segysak.segy import segy_header_scan

## Your uploaded SGY file now exists in memory
uploadedSGY = st.file_uploader("Upload file","SGY")

if uploadedSGY:

    ## Creates a file in writing mode
    with open("myTempFile.tmp",'w+b') as tempSGY:
        
        ## Writes the SGY to the file
        tempSGY.write(uploadedSGY.getbuffer())
        
        ## Now you can use that file path
        scan = segy_header_scan(tempSGY.name)
        
        ## Show the data
        st.dataframe(scan)

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.