Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
576 views
in Technique[技术] by (71.8m points)

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

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 = csv.DictReader(paramFile)
    list1 = []
    for row in data:
        list1.append(row)

    print list1

file.csv

12345,abcdef

output

[{'1': '', None: ['']}, {'1': '2'}]

I want to append all values in list1

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...