Halim
Halim

Reputation: 64

read a CSV file from post request

i am trying to get read some data from a CSV file but when I try read the file with the folwing method I get the error

ValueError: I/O operation on closed file.

def post(self, request):
        serializer = MosqueFileSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            file =pd.read_csv(request.FILES['file'])
        return Response(status=status.HTTP_200_OK)

and when i try to open the file i get another error

TypeError: expected str, bytes or os.PathLike object, not InMemoryUploadedFile

def post(self, request):
        serializer = MosqueFileSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            file =pd.read_csv(open(request.FILES['file']))
        return Response(status=status.HTTP_200_OK)

so can someone help me to find a solution?

Upvotes: 0

Views: 1031

Answers (1)

AlgRev
AlgRev

Reputation: 146

According to the documentation, the file pointer of an InMemoryUploadedFile object is at its .file attribute. The open function returns the InMemoryUploadedFile object itself.

Also open is a member function of InMemoryUploadedFile instance. So instead of open(request.FILES['file'])

I suggest you try

request.FILES['file'].open()
file = pd.read_csv(request.FILES['file'].file)

Edit: fixed the wrong call in previous version

Upvotes: 2

Related Questions