将上传的csv文件转换为Django中的列表

时间:2016-06-13 19:49:28

标签: python django csv django-forms django-views

当我尝试将django中上传的csv文件的第一列转换为列表时,我遇到了问题。最初,我的代码是这样的,没有使用django:

with open("export.csv") as f:
    my_list = [row["BASE_NAME"] for row in DictReader(f)]

但是在使用django开发用户界面时,我没有上面所需的my_list,我做错了什么?我尝试了许多方法,你可以在评论代码中看到:

这是我的view.py:

def handle_csv_data(csv_file):

    logging.warning('Watch out!')  # will print a message to the console
    #print(csv_file)
   # with open(csv_file) as f:
    #    my_list = [row["BASE_NAME"] for row in DictReader(f)]
    users = []
    for row in csv_file:
        users.append(row)

    return (users)

def home(request):
    if request.method=="POST":
        img = UploadForm(request.POST, request.FILES)
        if img.is_valid():
            logging.warning('Watch out!')  # will print a message to the console
           # paramFile = request.FILES['pic']
            paramFile =TextIOWrapper(request.FILES['pic'].file).read()
            portfolio1 = csv.DictReader(paramFile)

          #  portfolio = csv.DictReader(request.FILES['pic'].file)
           # csv_file = request.FILES['pic'].file
           # with open(default_storage.path('images/' + "500 clusters.csv"), 'wb+') as destination:
           #     for chunk in csv_file.chunks():
           #         destination.write(chunk)
           # ifile = open("500 clusters.csv", "r")
          #  data = [row for row in DictReader(csv_file.read().splitlines())]
           # print(users)
          #  paramFile = csv_file.read()
          #  portfolio1 = csv.DictReader(paramFile)
            #ifile = open('sample.csv', "r")
            #read = csv.reader(ifile)
            #for row in read:
             #   print(row)
            #data = [row for row in DictReader(csv_file.read().splitlines())]
          #  for row in portfolio:
           #    my_list = [row["BASE_NAME"]]

            #print(my_list)
            portfolio= handle_csv_data(portfolio1)
            print(portfolio)
           # my_list = portfolio

           # return HttpResponseRedirect(reverse('portfolio'))
            return render(request, 'home.html', {'portfolio': portfolio})
    else:
        img=UploadForm()
    images=Upload.objects.all()
    return render(request,'home.html',{'form':img,'images':images})

这是我的model.py:

from django.db import models
from django.forms import ModelForm

class Upload(models.Model):
    pic = models.FileField("pic", upload_to="images/")
    upload_date=models.DateTimeField(auto_now_add =True)

# FileUpload form class.
class UploadForm(ModelForm):
    class Meta:
        model = Upload
    fields = '__all__' 

我很感激帮助。

2 个答案:

答案 0 :(得分:5)

您的代码存在问题:

a

paramFile =TextIOWrapper(request.FILES['pic'].file).read() portfolio1 = csv.DictReader(paramFile) 期望一个可迭代的字符串(通常是文件对象),其中每个字符串代表一行。因为你调用了DictReader.read()是一个字符串,它是一个可迭代的字符串,但每个产生的字符串都是一个字符,而不是一行。删除paramFile

答案 1 :(得分:0)

tsc && babel build -d build --source-maps inline

通过查看本地主页中的局部变量,我能够通过以上方式修复它。