11

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 ?

2 Answers 2

25

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)
Sign up to request clarification or add additional context in comments.

Comments

3

I finally found a work around:

 reader = csv.reader(open(object.uploaded_file.path,'r'))

Instead of using built-in read() or open() of File object which has low documentation as I said in my question, I used the path attribute.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.