admin管理员组

文章数量:1287593

def createlist(request):
    if request.method == 'POST':
        files =  request.FILES['ListFile']
        print(type(files))
        csv_file = csv.DictReader(files)
        for i in csv_file:
            print(i)
    return HttpResponse("ok")

This gives
class 'django.core.files.uploadedfile.InMemoryUploadedFile'
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
Here i post this file using ajax
js:

$('#form1').ajaxForm(function(data) { 
           alert(data) ; 
        });
def createlist(request):
    if request.method == 'POST':
        files =  request.FILES['ListFile']
        print(type(files))
        csv_file = csv.DictReader(files)
        for i in csv_file:
            print(i)
    return HttpResponse("ok")

This gives
class 'django.core.files.uploadedfile.InMemoryUploadedFile'
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
Here i post this file using ajax
js:

$('#form1').ajaxForm(function(data) { 
           alert(data) ; 
        });
Share Improve this question asked May 29, 2014 at 7:18 itzMEonTVitzMEonTV 20.4k4 gold badges44 silver badges51 bronze badges 5
  • What does print([type(x) for x in files.readlines()]) give you? – dilbert Commented May 29, 2014 at 7:26
  • @dilbert [<class 'bytes'>, <class 'bytes'>, – itzMEonTV Commented May 29, 2014 at 7:39
  • DING, DING, DING, we have a winner!! – dilbert Commented May 29, 2014 at 7:42
  • @dilbert any solution to read files as dictreader to get as dictionary – itzMEonTV Commented May 29, 2014 at 7:45
  • You need to either a) change request.FILES['ListFile'] to a non-binary read mode or b) read all of request.FILES['ListFile'] into an intermediate file-like object. I would remend a). – dilbert Commented May 29, 2014 at 7:47
Add a ment  | 

2 Answers 2

Reset to default 14

Using codec.iterdecode, i solved it.I think this is due to python 3.x

import codecs

def createlist(request):
    if request.method == "POST":    
        fil =  request.FILES['ListFile']
        csvfile = csv.DictReader(codecs.iterdecode(fil, 'utf-8'))
        for i in csv_file:
            print(i)
    return HttpResponse("ok") 

The CSV doesn't support UTF8. It needs the file-like object to be encoded. Refer to here for more information.

import codecs

def createlist(request):
    if request.method == "POST":
        utf8_file = codecs.EncodedFile(request.FILES["ListFile"],"utf-8")
        csv_file = csv.DictReader(utf8_file)
        for i in csv_file:
            print(i)
    return HttpResponse("ok")

本文标签: javascriptdjango csv file upload managingStack Overflow