7

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.

1 Answer 1

10

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'))
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, it worked. Just a quick question, will it work for files with extensions xls or xlsx as well or just csv?
pandas.read_csv() is made for CSV input. If you want to read other formats, you need to use the other available methods such as pandas.read_excel() (which also accepts an opened file as input). You will have to detect the input type, for example by using the uploaded filename extension, or adding a post parameter whose value depends on the file format.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.