龙卷风:读取上传的CSV文件? [英] Tornado: Read uploaded CSV file?

查看:81
本文介绍了龙卷风:读取上传的CSV文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想执行以下操作:

import csv
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def post(self):
        uploaded_csv_file = self.request.files['file'][0]
        with uploaded_csv_file as csv_file:
            for row in csv.reader(csv_file):
                self.write(' , '.join(row))

但是, uploaded_csv_file 的类型不是 file

这里的最佳做法是什么?

What is the best practice here?

来源:

  • http://docs.python.org/2/library/csv.html
  • http://docs.python.org/2/library/functions.html#open
  • https://stackoverflow.com/a/11911972/242933

推荐答案

文档解释:


csvfile 可以是任何支持迭代器协议的对象,每次调用其 next()方法时都会返回一个字符串-文件对象和列表对象

csvfile can be any object which supports the iterator protocol and returns a string each time its next() method is called — file objects and list objects are both suitable.

因此,如果您拥有的东西不是文件,而是行的迭代器,那很好。如果它甚至不是行上的迭代器,则将其包装为一个。举一个简单的例子,如果它带有 read_all()方法,则可以始终这样做:

So, if you have something which is not a file, but is an iterator over lines, that's fine. If it's not even an iterator over lines, just wrap it in one. For a trivial example, if it's something with a read_all() method, you can always do this:

uploaded_csv_file = self.request.files['file'][0]
contents = uploaded_csv_file.read_all()
lines = contents.splitlines()
for row in csv.reader(lines):
    # ...

(显然,您可以将步骤合并在一起以使其更简短;我只是将每个步骤写为单独的一行,以使其更容易理解。)

(Obviously you can merge steps together to make it briefer; I just wrote each step as a separate line to make it simpler to understand.)

当然,如果CSV文件很大,并且特别是如果他们花了一段时间才能到达并且您有一个不错的流接口,那么您可能不希望一次阅读整个内容。大多数网络服务器框架都提供了不错的协议适配器,例如,获取字节流并为您提供行流。 (为此,即使是stdlib中的 socket.makefile()也可以做到这一点……)但就您而言,我认为这不是问题。

Of course if the CSV files are large, and especially if they take a while to arrive and you've got a nice streaming interface, you probably don't want to read the whole thing at once this way. Most network server frameworks offer nice protocol adapters to, e.g., take a stream of bytes and give you a stream of lines. (For that matter, even socket.makefile() in the stdlib sort of does that…) But in your case, I don't think that's an issue.

这篇关于龙卷风:读取上传的CSV文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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