Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Read uploaded CSV file using FileField instance

Tags:

python

csv

django

I'm trying to read the data of a .csv file uploaded by a user in a field of type FileField. I have no problem acessing the object, but I can't seem to make it work with the csv module. Here is what I'm trying:

reader = csv.reader(object.uploaded_file.read())
for rows in reader:
...

Where object is an instance of my model and uploaded_file the corresponding field.

I'm getting this error:

iterator should return strings, not int (did you open the file in text mode?)

Also,

I tried to use the open() method but whitout success. The documentation on this subject seems so vague. Even worst, the only thing I could find on the read() method used above is this:

In addition to the listed methods, File exposes the following attributes and methods of its file object: encoding, fileno, flush, isatty, newlines, read, readinto, readline, readlines, seek, softspace, tell, truncate, write, writelines, xreadlines, readable(), writable(), and seekable().

EDIT

I know it probably has to do with the reading mode has this thread suggest, but how can I change the mode in this case ?

like image 990
scharette Avatar asked Nov 15 '17 20:11

scharette


1 Answers

Here's my workaround (as you shouldn't need to 'open' an already opened file in the case of a FileField upload).

import csv
from io import StringIO

def parse_file(self, csv_upload):
    file = csv_upload.read().decode('utf-8')
    csv_data = csv.reader(StringIO(file), delimiter=',')
    for row in csv_data:
        print(row)
like image 64
AlxVallejo Avatar answered Oct 22 '22 14:10

AlxVallejo