zero-size array to reduction operation fmin which has no identity

Question:

I’m trying read xlsx file but gets me ValueError
zero-size array to reduction operation fmin which has no identity

views.py

def t(request):
    context = {} 

   if request.method == "POST":
    uploaded_file = request.FILES['document']
    print(uploaded_file)
    if uploaded_file.name.endswith('.xlsx'):
        
        savefile = FileSystemStorage()
        name = savefile.save(uploaded_file.name, uploaded_file) 
        d = os.getcwd() 
        file_directory = d + 'media\' + name
        readfile(file_directory)
        return redirect(r)
    else:
         messages.warning(request, 'File was not uploaded. Please use xlsx file extension!')

return render(request, 't.html', {})

def read_file(filename):

    my_file = pd.read_excel(filename)
    data = pd.DataFrame(data=my_file)

Note: It reads some files correctly

Asked By: OmarDev

||

Answers:

To avoid the error pointed out in the comments wrap the line of code with try/except. Check your logs which line throws the error, I think it is this one:

try:
    my_file = pd.read_excel(filename)
except ValueError:
    messages.error(request, "The file has the wrong format.")
    # or whatever error message you want to raise

Ideally, you want to raise the error before saving the file. I would try to read the file with pd before saving it:

# ...
uploaded_file = request.FILES['document']
if uploaded_file.name.endswith('.xlsx'):
    try:
        _read_test = pd.read_excel(uploaded_file)
    except ValueError:
        messages.error(request, "The file has the wrong format.")
        # or whatever error message you want to raise
        return redirect('your-error-or-form-page')

    savefile = FileSystemStorage()
    # ...

I’m not sure if pd can read the InMemoryFile but that’s the line where you want to catch wrong files. Maybe there’s already a pypi packages for cases like this

Answered By: hanspeters205