本文介绍了如何使用csv.DictReader在django中上传和读取csv文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过上传读取csv文件,并尝试将所有值存储在列表中

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

输出

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

我要在list1

推荐答案

您有两个问题:

  • 您正在将字符串传递给DictReader的构造函数.您必须传递一个可迭代的对象,该对象给出输入中的各行(字符串是可迭代的,但一次将每个字符赋予一个).幸运的是, UploadedFile 对象(如FILES词典中的对象)已经是支持迭代的类似文件的对象,因此只需执行以下操作:

  • 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'])

  • 您的输入数据只有一行. DictReader将使用该行作为标题"列,这将成为结果字典中的键.这样您将没有数据了!看来您不想要DictReader,只是想要 reader :

  • 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'])
    

  • 这篇关于如何使用csv.DictReader在django中上传和读取csv文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    09-22 06:21