Getting type error when opening downloaded CSV file

I am developing an application in python with django. User can download CSV file. I use file upload to get the file. But he does not store anywhere. I am trying to take it from a request to process a file. While I try to open the file, it gives an error. I am using the CSV library existing in python for processing. Form elements and attributes used for django. The request object that I am trying to load the downloaded file is also an object created by django.

import csv from rootFolder.UploadFileForm def uploadFile(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): paramFile = open(request.FILES['uploadFile'], 'rb') portfolio = csv.DictReader(paramFile) users = [] for row in portfolio: users.append(row) 

The line below indicates the error.

 paramFile = open(request.FILES['uploadFile'], 'rb') 

This error:

 TypeError: coercing to Unicode: need string or buffer, InMemoryUploadedFile found 

Please kindly give your suggestion if you have an idea about this. Thanks in advance.

+7
source share
4 answers

open () takes the file name as an argument, not the file itself.

Can you try something like this:

 paramFile = request.FILES['uploadFile'].read() portfolio = csv.DictReader(paramFile) 
+5
source

No need to open the file, it is already open. You should be able to pass it directly to DictReader.

+8
source

This works for Python 3.

 import csv import io ... csv_file = request.FILES['uploadFile'] decoded_file = csv_file.read().decode('utf-8') io_string = io.StringIO(decoded_file) for line in csv.reader(io_string, delimiter=';', quotechar='|'): print(line) 
+8
source

You get a TypeError because the built-in open function expects a string that is the path to the file.

It works?

  if form.is_valid(): request.FILES['uploadFile'].open("rb") portfolio = csv.DictReader(request.FILES['uploadFile'].file) 
0
source

All Articles