gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:42:01 31 4
gpt4 key购买 nike

当我尝试将 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})

这是我的模型.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__'

感谢您的帮助。

最佳答案

你的代码的问题在这里:

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

DictReader 需要一个可迭代的字符串(通常是一个文件对象),其中每个字符串代表一行。因为你调用了 .read()paramFile 是一个字符串,它是一个可迭代的字符串,但每个生成的字符串都是一个字符,而不是一行。删除 .read()

关于python - 将上传的 csv 文件转换为 Django 中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37798021/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com