使用Python Flask上传CSV文件并进行处理 [英] Upload CSV file using Python Flask and process it

查看:1063
本文介绍了使用Python Flask上传CSV文件并进行处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,可以使用Python FLASK上传CSV文件.

I have the following code to upload an CSV file using Python FLASK.

from flask_restful import Resource
import pandas as pd

ROOT_PATH = os.path.dirname(os.path.abspath(__file__))

class UploadCSV(Resource):

    def post(self):
        files = request.files['file']
        files.save(os.path.join(ROOT_PATH,files.filename))
        data = pd.read_csv(os.path.join(ROOT_PATH,files.filename))
        print(data)

api.add_resource(UploadCSV, '/v1/upload')

if __name__ == '__main__':
    app.run(host='localhost', debug=True, port=5000)

此代码可以正常工作,我可以成功上传CSV文件并使用pandas数据框读取它.但是我将csv保存在本地文件系统中并读取它.

This code works fine and I can able to upload CSV file successfully and read it using pandas dataframe. But I'm saving the csv in local filesystem and reading it.

我尝试过阅读如下内容-

I have tried reading like below -

files = request.files['file']
files.read()

获得的结果以字节格式显示,但我需要以字典格式显示.因此,我使用了pandas数据框来读取它,然后将其转换为自己格式的自定义词典.

The results obtained were in the format of bytes but I need it in the format of dictionary. So I used pandas dataframe to read it and I later convert it into a custom dictionary of my format.

是否可以在不将其写入本地文件系统的情况下即时读取CSV文件?还是我们可以使用Python Flask Restful实现的任何等效方法?

Is it possible to read the CSV file on the fly without writing it in local filesystem? Or any equivalent way we can achieve using Python Flask Restful?

推荐答案

(由于它是一个文件,因此名称不太恰当)files变量包含

The (not so aptly named, due to it being one file) files variable contains a werkzeug.datastructures.FileStorage object. This is a file like object (containing a read() method), and as such it is possible to use it directly as input to pandas.read_csv()as seen in the pandas documentation.

因此,不保存到磁盘的解决方案很简单:

Thus, the solution to not save to disk is as simple as:

class UploadCSV(Resource):

    def post(self):
        file = request.files['file']
        data = pd.read_csv(file)
        print(data)

这篇关于使用Python Flask上传CSV文件并进行处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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