how to upload and read csv file in django using csv.DictReader?

后端 未结 3 1693
灰色年华
灰色年华 2020-12-16 20:56

I am reading csv file through upload and trying to store all values in a list

def upload(request):
    paramFile = request.FILES[\'file\'].read()
    data =          


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-16 21:17

    You have two problems:

    • You are passing a string to the constructor of DictReader. You must pass an iterable object that gives the individual lines in the input (a string is iterable, but will give each character one at a time). Luckily, an UploadedFile object (like those in the FILES dictionary) are already file-like objects that support iteration, so just do this:

      data = csv.DictReader(request.FILES['file'])
      
    • Your input data only has one line. DictReader will use that line for the column "headers", which will become the key in the resulting dictionaries. You will then have no data left! It looks like you don't want a DictReader, just a regualar reader:

      data = csv.reader(request.FILES['file'])
      

提交回复
热议问题