在Django中解析和处理CSV [英] Parse and process CSV in Django
问题描述
自从我是Django的新手(在此之前,我还必须更新我的Python技能),向您道歉.我正在尝试举一个简单的示例,通过表单上传文件,然后在终端中打印行(作为进行某些实际处理之前的测试).我的views.py包含以下内容:
Apologies in advance since I'm new to Django (and I've also had to freshen up my Python skills). I'm trying to make a simple example of uploading a file through a form and then printing the rows in my terminal (as a test before doing some actual processing). My views.py contains the following:
def upload_csv(request):
if "GET" == request.method:
return render(request, "portal/csvupload.html")
csv_file = request.FILES["csv_file"]
handle_files(csv_file)
return HttpResponseRedirect(reverse("portal:csvupload"))
def handle_files(csvfile):
csv_reader = csv.reader(csvfile)
for line in csv_reader:
print(line)
现在,这将返回一条错误消息,内容为"预期的str,字节或os.PathLike对象,而不是InMemoryUploadedFile ",并且我不确定基于该错误消息的代码出了什么问题?从Python的角度来看,我认为它看起来不错,但也许与重定向有关?评估所有答案
Now this returns an error message saying "expected str, bytes or os.PathLike object, not InMemoryUploadedFile", and I'm unsure what's wrong with the code based on the error message? From a Python perspective it looks fine I think, but perhaps it's something to do with the re-direct? Apperciate all answers
推荐答案
request.FILES["csv_file"]
返回一个InMemoryUploadedFile
对象,而csv.reader
不知道如何处理这样的对象.我相信您需要调用对象的read
方法:handle_files(csv_file.read())
.请注意警告文档中的a>:请谨慎使用此方法:如果上载的文件很大,如果尝试将其读取到内存中,可能会使您的系统不堪重负.您可能想改用chunks();请参见下文."
request.FILES["csv_file"]
is returning an InMemoryUploadedFile
object and csv.reader
does not know how to handle such an object. I believe you need to call the object's read
method: handle_files(csv_file.read())
. Note the warning in the documentation: "Be careful with this method: if the uploaded file is huge it can overwhelm your system if you try to read it into memory. You’ll probably want to use chunks() instead; see below."
这篇关于在Django中解析和处理CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!