0

I built a form with a FileField in order to upload file to be processed. Strangely it seem that file is closed before I can do anything with in the view. I encounter a ValueError after validating the form:

"I/O operation on closed file"

I can see that file is properly detected but closed when attempting to read it.

Note: Django version 2.2.25.

forms.py

class FileImportForm(forms.Form):
    headers = ["lastname","firstname","gender","title","entity","email","company","address","phone"]
    file = forms.FileField(label='CSV file',validators=[CsvFileValidator(headers)])
    
    def clean_file(self):
        file = self.cleaned_data['file']
        return file   

views.py

@login_required
def file_import(request):
    if request.method == 'POST': 
        form = FileImportForm(request.POST,request.FILES)

        if form.is_valid():
            if request.FILES['file']:
                file_post = request.FILES['file']
                # Offending line below (I/O operation on closed file)
                file_content = file_post.read().decode('UTF-8')

                return redirect("/foo")
    else:
        form = FileImportForm()
    
    return render(request,"file_import.html", { 'form': form })

How to properly process uploaded file (read, etc..)?

1 Answer 1

1

The error occurs because you didn't open your file properly. Here's the working way:

file_post = request.FILES['file']
f = open(file_post, "w")

As python's file operation also comes with a read-only method, you cannot do file_content = file_post.read().decode('UTF-8') directly because you didn't make this file writable.

Reference.

EDIT

As the upload file type may be incorrect, more conversions are needed. Something like:

def my_view(request):
    uploaded_file = request.FILES['file']
    str_text = ''
    for line in uploaded_file:
        str_text = str_text + line.decode()  # "str_text" will be of `str` type
    # do something
    return something

Reference2

Sign up to request clarification or add additional context in comments.

7 Comments

This doesn't work, it throws a TypeError exception "expected str, bytes or os.PathLike object, not InMemoryUploadedFile". Type is not one of expected types for open.
Probably you should consider some other way then. As the demo stuck with txt files, probably InMemoryUploadedFile is another type that doesn't fit with python's rules
I just edited my answer. Can you make use of my edit?
Exception "I/O operation on closed file" this time. Somehow raw file content need to be converted.
The second reference I put up there had this: uploaded_file.read(). If you're trying to actually write the file, you might be looking for something else.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.