1

I would like to show information from a csv file on my flask app on a table but it only shows the first line of the csv file.

@app.route('/view/', methods=['GET', 'POST'])
def view():
    with open('/home/MakerofMarkers/mysite/container.csv', 'r') as csv_file:
        csv_reader = csv.reader(csv_file)
        next(csv_reader)

        for line in csv_reader:
            return str(line)

    return render_template('work.html')
mark
  • 81
  • 1
  • 9
  • Do you want it to display the entire csv file inside your work.html page? – Akib Rhast May 30 '20 at 16:47
  • Stating "I would like to show information from a csv file on my flask app" is not providing enough information as to how, exactly, you want to present the information to the user of the site. As to why only the first line is displayed - that's an easy one: when you supposedly iterate over all CSV lines, you immediately `return` in the loop body, causing just the text/JSON of the first line to be returned. – Amitai Irron May 30 '20 at 16:51
  • Sorry for the unclear question. I would like the csv data to be shown in a table. – mark May 30 '20 at 17:07
  • I would like to display the entire csv file on my work.html page – mark May 30 '20 at 17:12

1 Answers1

2

If youre are using flask, in the render_template you send the data to the html in a variable

@app.route('/view/', methods=['GET', 'POST'])
    def view():
        with open('/home/MakerofMarkers/mysite/container.csv', 'r') as csv_file:
            csv_reader = csv.reader(csv_file)

        return render_template('work.html', data = csv_reader)

This is a example of work.html

<div class="card-body">
            <table class="table table-hover">
                <thead>
                    <tr>
                    <th scope="col">#</th>
                    <th scope="col">Data1</th>
                    <th scope="col">Data2</th>
                    <th scope="col">Data3</th>
                    <th scope="col">Data4</th>
                    <th scope="col">Data5</th>

                    </tr>
                </thead>
                <tbody>
                    {% for line in data %}
                    <tr>
                        <td>{{line.id}}</td>
                        <td>{{line.data1}}</td>
                        <td>{{line.data2}}</td>
                        <td>{{line.data3}}</td>
                        <td>{{line.data4}}</td>
                        <td>{{line.data5}}</td>
                    </tr> 
                    {% endfor %}                        
                </tbody>
            </table>
        </div>

Use jinja2, the data is used with {% %} In this case i using line.data1, if your lines are list modify this to line[1] for example

gañañufla
  • 552
  • 2
  • 12