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

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

问题描述

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

  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:需要字符串或缓冲区,InMemoryUploadedFile找到

请提出您的建议,任何想法。
提前感谢。

解决方案

open()使用文件的名称作为参数而不是文件对象



您可以尝试这样:

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


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)

This below line gives the error.

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

The given error is :

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() takes the name of the file as the argument and not the file object itself.

Can you try something like this:

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

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

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