简体   繁体   中英

Parse .csv file in tornado web server

I'm trying to parse a.csv file using this code

class uploadHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("index.html")
        
    def post(self):
    
        file = self.request.files['uploadedFile'][0]
        filename = file['filename']

        output = open("file/" + filename, 'wb')
        output.write(file['body'])
        self.write("http://localhost:8080/file/" + filename)
        self.finish("uploaded")
        
        df = pandas.read_csv("file\\" + filename)
        print(df)
        

if (__name__ == "__main__"):
    app = tornado.web.Application([
        ("/", uploadHandler),
        ("/file/(.*)", tornado.web.StaticFileHandler, {"path" : "file"})
    ])
    
    app.listen(8080)
    print("Listening on port 8080")
    
    tornado.ioloop.IOLoop.instance().start()

I get the error

File "pandas\_libs\parsers.pyx", line 554, in pandas._libs.parsers.TextReader.__cinit__
pandas.errors.EmptyDataError: No columns to parse from file

How can I parse this file?

I tried accessing this file in different parts of the code but I get the same error. The file gets uploaded correctly.

You have to close the output handler before read the file with Pandas:

...
        output = open("file/" + filename, 'wb')
        output.write(file['body'])
        output.close()  # <- HERE
...

But use a context manager instead of closing the file yourself:

...
        with open("file/" + filename, 'wb') as output:
            output.write(file['body'])
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM