Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Type error while opening an uploaded CSV File

I'm developing an application in python with django. User can upload a CSV file. I use file upload to get the file. But, it's not stored any where. I try to take it from request to process the file. While I'm trying to open the file, it gives an error. I use the CSV library exists in python to process. Form elements and attributes used as per django. Request object which I try to take the uploaded file is also django designed object.

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)

This below line gives the error.

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

The given error is :

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

Please kindly give your suggestion if you got any idea on this. Thanks in advance.

like image 435
Nazneen Avatar asked May 16 '12 11:05

Nazneen


People also ask

Why CSV file is not opening?

CSV (comma delimited) will not open correctly and the data within will be displayed incorrectly. This is due to regional Excel settings that have default list separator options where files will either be read with a comma separator or semicolon separator.


1 Answers

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)
like image 166
Mark Mishyn Avatar answered Oct 13 '22 00:10

Mark Mishyn