The Wayback Machine - https://web.archive.org/web/20240909100607/https://www.geeksforgeeks.org/convert-csv-to-html-table-using-python-pandas-and-flask-framework/
Open In App

Convert CSV to HTML Table using Python Pandas and Flask Framework

Last Updated : 26 May, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we are going to convert a CSV file into an HTML table using Python Pandas and Flask Framework.

Sample CSV file :

USERNAME,IDENTIFIER,FIRST_NAME,LAST_NAME
booker12,9012,Rachel,Booker
grey07,2070,Laura,Grey
johnson81,4081,Craig,Johnson
jenkins46,9346,Mary,Jenkins
smith79,5079,Jamie,Smith

Stepwise Implementation

Creating Environment

Step 1: Create an environment. Create a project folder and a venv folder within.

py -3 -m venv venv

Step 2: Activate the environment.

venv\Scripts\activate

Step 3: Install Flask and Pandas.

pip install Flask

pip install pandas

Creating Project

Step 1: Create ‘app.py’ folder and write the code given below.

Python3




# importing flask
from flask import Flask, render_template
  
# importing pandas module
import pandas as pd
  
  
app = Flask(__name__)
  
  
# reading the data in the csv file
df = pd.read_csv('sample_data.csv')
df.to_csv('sample_data.csv', index=None)
  
  
# route to html page - "table"
@app.route('/')
@app.route('/table')
def table():
    
    # converting csv to html
    data = pd.read_csv('sample_data.csv')
    return render_template('table.html', tables=[data.to_html()], titles=[''])
  
  
if __name__ == "__main__":
    app.run(host="localhost", port=int("5000"))


Step 2: Create the folder ‘templates’. create the file ‘table.html’ inside the ‘templates’ folder.

HTML




<!DOCTYPE html>
<html lang="en">
    <head>
        <title> Table </title>              
    </head>
    <body>
        <div align="center">
            <table>
                <h1>
                <!--Displaying the converted table-->
                     {% for table in tables %}
                    <h2>{{titles[loop.index]}}</h2>                            
                    {{ table|safe }}
                    {% endfor %}     
                </h1> 
            </table>
        </div>
    </body>
</html>


Step 3: Add the ‘sample_data.csv’ file.

Step 4: The project structure will look like this.

Structure of  the project

Run the Project

Step 1: Run the server.

Step 2: Browse the URL ‘localhost:5000’.

Step 3: The output web page will be displayed.

Output:

Output : CSV to HTML Table



Similar Reads

How to create multiple CSV files from existing CSV file using Pandas ?
In this article, we will learn how to create multiple CSV files from existing CSV file using Pandas. When we enter our code into production, we will need to deal with editing our data files. Due to the large size of the data file, we will encounter more problems, so we divided this file into some small files based on some criteria like splitting in
3 min read
Minify HTML in Flask using Flask-Minify
Flask offers HTML rendering as output, it is usually desired that the output HTML should be concise and it serves the purpose as well. In this article, we would display minification of output routes of Flask responses using the library - Flask-Minify. Advantages of MinificationWebsites load faster as fewer lines are there to upload and download.Ban
12 min read
Convert CSV to HTML Table in Python
CSV file is a Comma Separated Value file that uses a comma to separate values. It is basically used for exchanging data between different applications. In this, individual rows are separated by a newline. Fields of data in each row are delimited with a comma.Example : Name, Salary, Age, No.of years employed Akriti, 90000, 20, 1 Shreya, 100000, 21,
2 min read
Convert HTML table into CSV file in python
CSV file is a Comma Separated Value file that uses a comma to separate values. CSV file is a useful thing in today's world when we are talking about machine learning, data handling, and data visualization. In this article, we will discuss how to convert an HTML table into a CSV file. Converting HTML Table into CSV file in Python Example: Suppose HT
2 min read
Wikipedia search app using Flask Framework - Python
Flask is a micro web framework written in Python. It is classified as a micro-framework because it does not require particular tools or libraries. Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. Installation: 1) In order to create the
2 min read
Documenting Flask Endpoint using Flask-Autodoc
Documentation of endpoints is an essential task in web development and being able to apply it in different frameworks is always a utility. This article discusses how endpoints in Flask can be decorated to generate good documentation of them using the Flask-Autodoc module. This module provides the following features - Helps to document endpoints of
4 min read
How to use Flask-Session in Python Flask ?
Flask Session - Flask-Session is an extension for Flask that supports Server-side Session to your application.The Session is the time between the client logs in to the server and logs out of the server.The data that is required to be saved in the Session is stored in a temporary directory on the server.The data in the Session is stored on the top o
4 min read
How to Integrate Flask-Admin and Flask-Login
In order to merge the admin and login pages, we can utilize a short form or any other login method that only requires the username and password. This is known as integrating the admin page and Flask login since it simply redirects users to the admin page when they log in. Let's is how to implement this in this article. Integrate Flask Admin and Fla
8 min read
Copying Csv Data Into Csv Files Using Python
CSV files, the stalwarts of information exchange, can be effortlessly harnessed to extract specific data or merge insights from multiple files. In this article, we unveil five robust approaches, transforming you into a virtuoso of CSV data migration in Python. Empower your data-wrangling endeavors, mastering the art of copying and organizing inform
4 min read
Convert CSV to Excel using Pandas in Python
Pandas can read, filter, and re-arrange small and large datasets and output them in a range of formats including Excel. In this article, we will be dealing with the conversion of .csv file into excel (.xlsx). Pandas provide the ExcelWriter class for writing data frame objects to excel sheets. Syntax: final = pd.ExcelWriter('GFG.xlsx') Example:Sampl
1 min read
Convert Text File to CSV using Python Pandas
Let's see how to Convert Text File to CSV using Python Pandas. Python will read data from a text file and will create a dataframe with rows equal to number of lines present in the text file and columns equal to the number of fields present in a single line. See below example for better understanding. Dataframe created from upper text file will look
2 min read
Flask URL Helper Function - Flask url_for()
In this article, we are going to learn about the flask url_for() function of the flask URL helper in Python. Flask is a straightforward, speedy, scalable library, used for building, compact web applications. It is a micro framework, that presents developers, useful tools, and, features, for coding REST APIs, and backend data processing, of web apps
11 min read
Uploading and Reading a CSV File in Flask
Flask is a flexible, lightweight web-development framework built using python. A Flask application is a Python script that runs on a web server, which listens to HTTP requests and returns responses. It is designed for simple and faster development. In this article, let's upload a CSV (Comma-Separated Values) file and read the contents of the file o
3 min read
How to create CSV output in Flask?
In this article, we will see how to create a CSV output using Flask. Python and Flask Web Frameworks provide powerful tools to generate a report, export data and create catalogs. We will see how to generate both CSV files using Python and Flask. Creating CSV files in Python FlaskStep 1: InstallationWe are using Flask to create CSV output. Please re
3 min read
Flask vs Django - Which Framework Should You Choose in 2024
Python isn't just a language; it's a powerhouse of tools that can make a developer's life a whole lot easier. And when it comes to building web applications, Flask and Django are two names that shine brightly. These frameworks are like toolboxes, filled with everything you need to create powerful, elegant web apps without getting bogged down in the
8 min read
Difference between Server-Side AJAX framework and Client-side AJAX framework ?
The article focuses on discussing the differences between the Server-side AJAX framework and the Client-side AJAX framework. The following topics will be discussed here: What is a Server-side AJAX framework?What is a Client-side AJAX framework?Server-side AJAX framework vs Client-side AJAX framework Let's start discussing each of these topics in de
3 min read
How to export HTML table to CSV using JavaScript ?
Comma Separated Values or CSV is a type of text file where each value is delimited by a comma. CSV files are very useful for the import and export of data to other software applications. Sometimes while developing web applications, you may come into a scenario where you need to download a CSV file converted from an HTML table. In this post, let us
6 min read
Rendering Data-Frame to html template in table view using Django Framework
In Django, It is easy to render the HTML templates by setting URLs of respective HTML pages. Here we will let to know about how we can work with DataFrame to modify them for table view in the HTML template or web-pages, and for that, we have to use 'render' and 'HttpResponse' functions to manipulate the data inside the DataFrame. Sample DataFrame:
3 min read
Convert CSV to Pandas Dataframe
In this article, we will discuss how to convert CSV to Pandas Dataframe, this operation can be performed using pandas.read_csv reads a comma-separated values (csv) file into DataFrame. Example 1: In the below program we are going to convert nba.csv into a data frame and then display it. Python Code # import pandas module import pandas as pd # makin
1 min read
Scrape and Save Table Data in CSV file using Selenium in Python
Selenium WebDriver is an open-source API that allows you to interact with a browser in the same way a real user would and its scripts are written in various languages i.e. Python, Java, C#, etc. Here we will be working with python to scrape data from tables on the web and store it as a CSV file. As Google Chrome is the most popular browser, to make
3 min read
How to Import a CSV file into a SQLite database Table using Python?
In this article, we are going to discuss how to import a CSV file content into an SQLite database table using Python. Approach:At first, we import csv module (to work with csv file) and sqlite3 module (to populate the database table).Then we connect to our geeks database using the sqlite3.connect() method.At this point, we create a cursor object to
3 min read
How to merge two csv files by specific column using Pandas in Python?
In this article, we are going to discuss how to merge two CSV files there is a function in pandas library pandas.merge(). Merging means nothing but combining two datasets together into one based on common attributes or column. Syntax: pandas.merge() Parameters : data1, data2: Dataframes used for merging.how: {‘left’, ‘right’, ‘outer’, ‘inner’}, def
3 min read
Display the Pandas DataFrame in table style and border around the table and not around the rows
Let us see how to style a Pandas DataFrame such that it has a border around the table. We will be using the set_table_styles() method of the Styler class in the Pandas module. set_table_styles() Syntax : set_table_styles(self, table_styles) Parameters : table_styles : List, each individual table_style should be a dictionary with selector and props
1 min read
How to Convert an image to NumPy array and saveit to CSV file using Python?
Let's see how to Convert an image to NumPy array and then save that array into CSV file in Python? First, we will learn about how to convert an image to a numpy ndarray. There are many methods to convert an image to ndarray, few of them are: Method 1: Using PIL and NumPy library. We will use PIL.Image.open() and numpy.asarray(). Example: C/C++ Code
4 min read
How to import data from .CSV file into MySQL table using Node.js ?
What is .CSV file? The .CSV (Comma Separated Values) files are plain text files that contains a list of data separated by comma(,). It is a format best used for tabular data, row, and columns, exactly like a spreadsheet, just the difference is that the file is in the form of plain text. The idea of a CSV file is to perform export and import complex
4 min read
How to convert CSV File to PDF File using Python?
In this article, we will learn how to do Conversion of CSV to PDF file format. This simple task can be easily done using two Steps : Firstly, We convert our CSV file to HTML using the PandasIn the Second Step, we use PDFkit Python API to convert our HTML file to the PDF file format. Approach: 1. Converting CSV file to HTML using Pandas Framework. P
3 min read
Convert PDF to CSV using Python
Python is a high-level, general-purpose, and very popular programming language. Python programming language (the latest Python 3) is being used in web development, Machine Learning applications, along with all cutting-edge technology in Software Industry. Python Programming Language is very well suited for Beginners, also for experienced programmer
2 min read
Using csv module to read the data in Pandas
The so-called CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. There were various formats of CSV until its standardization. The lack of a well-defined standard means that subtle differences often exist in the data produced and consumed by different applications. These differences can ma
3 min read
How to skip rows while reading csv file using Pandas?
Python is a good language for doing data analysis because of the amazing ecosystem of data-centric python packages. Pandas package is one of them and makes importing and analyzing data so much easier. Here, we will discuss how to skip rows while reading csv file. We will use read_csv() method of Pandas library for this task. Syntax: pd.read_csv(fil
3 min read
Pandas - DataFrame to CSV file using tab separator
Let's see how to convert a DataFrame to a CSV file using the tab separator. We will be using the to_csv() method to save a DataFrame as a csv file. To save the DataFrame with tab separators, we have to pass "\t" as the sep parameter in the to_csv() method. Approach : Import the Pandas and Numpy modules.Create a DataFrame using the DataFrame() metho
1 min read