Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting raw file content from Flask file upload into dataframe using pandas

I am trying to upload a csv file to my flask server. What I want to do is to read its content into a dataframe without saving it on the file system. For now I'm using the file.read() method to get the contents of the file, but I'm at loss when it comes to converting these content into a pandas dataframe. Here's the code:

@app.route('/upload', methods=['POST'])
def upload():
    file = request.files.get('uploaded_file')
    filename = secure_filename(file.filename)

    file_content = file.read()
    # want to convert these file content into a pandas dataframe

I am able to load it as a dataframe when saving to the disk, but I want to parse the content without saving the uploaded file.

like image 407
Ahmed Dhanani Avatar asked Oct 02 '17 08:10

Ahmed Dhanani


People also ask

How do I transfer files from a flask?

Python for web development using Flask Handling file upload in Flask is very easy. It needs an HTML form with its enctype attribute set to 'multipart/form-data', posting the file to a URL. The URL handler fetches file from request. files[] object and saves it to the desired location.

How do you import a sample data set using pandas?

First, you will import the pandas library and then pass the URL to the pd. read_json() which will return a dataframe. The columns of the dataframes represent the keys, and the rows are the values of the JSON.


1 Answers

pandas.read_csv() can take any file-like object (with a read() method) as input, so just use it: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html#pandas.read_csv

@app.route('/upload', methods=['POST'])
def upload():
    df = pandas.read_csv(request.files.get('uploaded_file'))
like image 191
Guillaume Avatar answered Sep 30 '22 10:09

Guillaume