从cgi.FieldStorage实例中读取文本

时间:2014-05-10 04:07:23

标签: python google-app-engine csv cgi

我试图阅读通过多部分POST上传的制表符分隔文本文件。我使用Python / Webapp2 / Jinja2在Google App Engine上运行此代码。

我在下面的行中收到此错误:" AttributeError :(两个下划线)退出(两个下划线)"

你能告诉我我做错了什么,以及如何使这项工作成功?谢谢!

class FileReader(webapp2.RequestHandler):

def post(self):

    field_storage = self.request.POST.get("file", None)
    if isinstance(field_storage.file, cgi.FieldStorage):

        with field_storage as csvfile:    ## This line causes an error "AttributeError: __exit__"
        reader = csv.reader(csvfile, dialect=csv.excel_tab)

        for row in reader:
            ...

1 个答案:

答案 0 :(得分:0)

field_storage.file是一个StringIO对象。没有必要打开它,因为它已经是一个打开的文件对象。

因此,请跳过并尝试:

reader = csv.reader(field_storage.file, dialect=csv.excel_tab)