-2

I am trying to build an flask app, which would load a csv file , assign it to the memory and then display the content on HTML page,

code that I am using as below, when I run the code and try to load the file, I get following error,

AttributeError: '_io.BytesIO' object has no attribute 'file

Flask

@app.route('/upload', methods=['GET', 'POST'])
def upload():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

            ## snippet to read code below
            file.stream.seek(0) # seek to the beginning of file
            myfile = file.file # will point to tempfile itself
            dataframe = pd.read_csv(myfile)
            ## end snippet

            return "yatta"
        else:
            return "file not allowed"

    return render_template("upload.html")

HTML

<div class="form-group">
    <form method="POST" enctype=multipart/form-data>
    <input class="btn btn-sm btn-primary" type="file" name="file">
    <input type="submit" value='upload'>
</div>
<table border="1" cellpadding="5" cellspacing="5">
            {% for row in data %}
                <tr>
                {% for d in row %}
                    <td>{{ d }}</td>
                {% endfor %}
            </tr>
            {% endfor %}
        </table>
Vikram Karthic
  • 468
  • 4
  • 18
  • Possible duplicate of [Opening csv file in Python: builtins. AttributeError AttributeError: '\_io.BytesIO' object has no attribute 'file'](https://stackoverflow.com/questions/44005053/opening-csv-file-in-python-builtins-attributeerror-attributeerror-io-bytesi) – Fine May 10 '18 at 08:22

1 Answers1

0

I am not familiar with this specific implementation, but since you use file.stream.seek(0), I think

myfile = file.stream

will solve your problem - partially.

While partially? Because your stream is bytestream - and if you are using Python3, pandas.read_csv requires text file/stream - i.e. unicode.

I used this conversion to solve the issue

unicode_stream = io.StringIO(download_stream.getvalue().decode())
volcano
  • 3,578
  • 21
  • 28
  • thanks you, I tried as per you suggestion, `unicode_stream = io.StringIO(download_stream.getvalue().decode())` `myfile = unicode_stream.read(request.files['file'])` `csvfile = csv.DictReader(myfile)` when I try this I get " NameError: name 'download_stream' is not defined" error – Vikram Karthic May 14 '18 at 06:13
  • that was just a quote from my code - _download_steam_ being of type _io.ByresIO_. – volcano May 14 '18 at 09:05