简体   繁体   English

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

[英]Convert uploaded csv file into list in Django

I'm having a problem when I'm trying to convert the the first column of the uploaded csv file in django into a list. 当我尝试将django中上传的csv文件的第一列转换为列表时,我遇到了问题。 Originally, my code was like this without using django: 最初,我的代码是这样的,没有使用django:

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

But when developing the user interface using django , I'm not having the required my_list like above, what am I doing wrong? 但是在使用django开发用户界面时,我没有上面所需的my_list ,我做错了什么? I tried many methods that you can see in the commented codes: 我尝试了许多方法,你可以在评论代码中看到:

Here is my view.py: 这是我的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})

Here is my model.py: 这是我的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__' 

I appreciate the help. 我很感激帮助。

The problem with your code is here: 您的代码存在问题:

paramFile =TextIOWrapper(request.FILES['pic'].file).read()
portfolio1 = csv.DictReader(paramFile)

DictReader expects an iterable of strings (usually a file object), where each string represents a line. DictReader期望一个可迭代的字符串(通常是文件对象),其中每个字符串代表一行。 Because you called .read() , paramFile is a string, which is an iterable of strings but each yielded string is a character, not a line. 因为您调用了.read()paramFile是一个字符串,它是一个可迭代的字符串,但每个产生的字符串都是一个字符,而不是一行。 Remove the .read() . 删除.read()

   paramFile =io.TextIOWrapper(request.FILES['pic'].file)
   portfolio1 = csv.DictReader(paramFile)
   print(type(paramFile))
    users = []
    users = [row["BASE_NAME"] for row in portfolio1]
    print(len(users))

Somehow I was able to fix it with the above, by looking at the local variables in the local host page. 通过查看本地主机页面中的局部变量,我能够通过以上方式修复它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM