打开上传的 CSV 文件时出现类型错误 [英] Getting Type error while opening an uploaded CSV File

查看:24
本文介绍了打开上传的 CSV 文件时出现类型错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 django 在 python 中开发一个应用程序.用户可以上传 CSV 文件.我使用文件上传来获取文件.但是,它没有存储在任何地方.我尝试从请求中获取它来处理文件.当我试图打开文件时,它给出了一个错误.我使用python中存在的CSV库来处理.按照 django 使用的表单元素和属性.我尝试获取上传文件的请求对象也是django设计的对象.

I'm developing an application in python with django. User can upload a CSV file. I use file upload to get the file. But, it's not stored any where. I try to take it from request to process the file. While I'm trying to open the file, it gives an error. I use the CSV library exists in python to process. Form elements and attributes used as per django. Request object which I try to take the uploaded file is also django designed object.

import csv
from rootFolder.UploadFileForm

def uploadFile(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            paramFile = open(request.FILES['uploadFile'], 'rb')
            portfolio = csv.DictReader(paramFile)
            users = []
            for row in portfolio:
                users.append(row)

下面这行给出了错误.

paramFile = open(request.FILES['uploadFile'], 'rb')

给定的错误是:

TypeError: coercing to Unicode: need string or buffer, InMemoryUploadedFile found

如果您对此有任何想法,请提出您的建议.提前致谢.

Please kindly give your suggestion if you got any idea on this. Thanks in advance.

推荐答案

open() 将文件名作为参数,而不是文件对象本身.

open() takes the name of the file as the argument and not the file object itself.

你能不能试试这样的:

paramFile = request.FILES['uploadFile'].read()
portfolio = csv.DictReader(paramFile)

这篇关于打开上传的 CSV 文件时出现类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆