Getting Type error while opening an uploaded CSV F

2020-02-05 03:21发布

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.

5条回答
何必那么认真
2楼-- · 2020-02-05 03:37

No need to call open on the file, it's already open. You should be able to pass it straight into the DictReader.

查看更多
趁早两清
3楼-- · 2020-02-05 03:39

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

Does this work?

    if form.is_valid():
        request.FILES['uploadFile'].open("rb")
        portfolio = csv.DictReader(request.FILES['uploadFile'].file)
查看更多
Ridiculous、
4楼-- · 2020-02-05 03:51

Django 2, Python 3.6, same problem, half a day of googling, this is the solution that worked for me.

form.is_valid:
  csv_file = request.FILES['file']
  csv_file.seek(0)
  reader = csv.DictReader(io.StringIO(csv_file.read().decode('utf-8')))

  for row in reader
     .....
     .....

detailed writeup here -> source

查看更多
beautiful°
5楼-- · 2020-02-05 03:54

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)
查看更多
劳资没心,怎么记你
6楼-- · 2020-02-05 03:56

open() takes the name of the file as the argument and not the file object itself.

Can you try something like this:

paramFile = request.FILES['uploadFile'].read()
portfolio = csv.DictReader(paramFile)
查看更多
登录 后发表回答