[Fixed]-Getting Type error while opening an uploaded CSV File

11👍

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)

21👍

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)

13👍

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

10👍

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

👤Shobi

1👍

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)
👤Schuh

Leave a comment