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

后端 未结 3 1685
灰色年华
灰色年华 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:12

    This should work if you're using Python 3.

    file = request.FILES['file'] 
    decoded_file = file.read().decode('utf-8').splitlines()
    reader = csv.DictReader(decoded_file)
    for row in reader:
        # Get each cell value based on key-value pair. 
        # Key will always be what lies on the first row.
    

    We can use the list that splitlines() creates. splitlines() is called because csv.DictReader expects "any object which supports the iterator protocol and returns a string each time its next() method is called — file objects and list objects are both suitable".

提交回复
热议问题