• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / Convert CSV to HTML Table in Python

Convert CSV to HTML Table in Python

Author: Aditya Raj
Last Updated: July 10, 2022

CSV files contain comma-separated values that usually contain tabular. Sometimes, we might need to render a csv file into an HTML page. In this article, we will discuss how we can convert a csv file to an HTML table in python. 

Convert CSV to HTML Table Using the pandas Module

The pandas module provides us with different tools to handle csv files. To convert a csv file to an HTML table, we will first open the file using the read_csv() method. The read_csv() method takes the file name of the csv file as an input argument and returns a dataframe containing the data from the csv file. 

After obtaining the data from the csv file into the dataframe, we can convert the dataframe into an HTML string using the to_html() method. The to_html() method, when invoked on a dataframe, converts the dataframe into an HTML table and returns the HTML text in the form of a string. You can observe this in the following example.

import pandas as pd

df1 = pd.read_csv('student_details.csv')
print("The dataframe is:")
print(df1)
html_string = df1.to_html()
print("The html string is:")
print(html_string)

Output:

The dataframe is:
     Name  Roll Number      Subject
0  Aditya           12       Python
1     Sam           23         Java
2   Chris           11          C++
3    Joel           10   JavaScript
4  Mayank            5   Typescript
The html string is:
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>Name</th>
      <th>Roll Number</th>
      <th>Subject</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>Aditya</td>
      <td>12</td>
      <td>Python</td>
    </tr>
    <tr>
      <th>1</th>
      <td>Sam</td>
      <td>23</td>
      <td>Java</td>
    </tr>
    <tr>
      <th>2</th>
      <td>Chris</td>
      <td>11</td>
      <td>C++</td>
    </tr>
    <tr>
      <th>3</th>
      <td>Joel</td>
      <td>10</td>
      <td>JavaScript</td>
    </tr>
    <tr>
      <th>4</th>
      <td>Mayank</td>
      <td>5</td>
      <td>Typescript</td>
    </tr>
  </tbody>
</table>

You can also save the data directly into an HTML file. For this, you have to pass the filename as an input argument to the to_html() method. The to_html() method, when invoked on a dataframe, takes the file name of the HTML file as an input argument and saves it in the current working directory. After execution, the to_html() method returns None in this case. You can observe this in the following example.

import pandas as pd

df1 = pd.read_csv('student_details.csv')
print("The dataframe is:")
print(df1)
df1.to_html("html_output.html")
print("CSV file saved into html file.")

Output:

The dataframe is:
     Name  Roll Number      Subject
0  Aditya           12       Python
1     Sam           23         Java
2   Chris           11          C++
3    Joel           10   JavaScript
4  Mayank            5   Typescript
CSV file saved into html file.

Following is the snapshot of the html table created using the above program.

Convert CSV to HTML Table Using the PrettyTable Module

We can also convert a csv file into an HTML file using the PrettyTable() method. For this, we will first open the csv file using the open() method in the read mode. The open() method takes the filename as its first input argument and the literal ‘r’ as its second input argument. After execution, it returns a file object containing the file content.

After opening the file, we will read the file content using the readlines() method. The readlines() method, when invoked on a file object, returns the contents of the file as a list of strings where each element of the list contains a line from the input file. 

Now, the header of the csv file will be present at the index 0 in the list returned by the readlines() method. We will extract the name of the columns of the csv files using the string split operation on the first element of the list returned by the readlines() method.

After obtaining the column names in a list, we will create a pretty table using the PrettyTable() method. The PrettyTable() method takes a list containing the column names as its input argument and returns a pretty table. After creating the table, we will add the data to the table using the add_row() method. The add_row() method takes a list containing the values in a row and adds it to the pretty table. 

After creating the table, we will obtain the HTML string of the table using the get_html_string() method. The get_html_string() method, when invoked on a pretty table object, returns the HTML text of the table in the form of a string. 

You can observe this entire process in the following example.

import prettytable

csv_file = open('student_details.csv', 'r')
data = csv_file.readlines()
column_names = data[0].split(',')
table = prettytable.PrettyTable()
table.add_row(column_names)
for i in range(1, len(data)):
    row = data[i].split(",")
    table.add_row(row)
html_string = table.get_html_string()
print("The html string obtained from the csv file is:")
print(html_string)

Output:

The html string obtained from the csv file is:
<table>
    <thead>
        <tr>
            <th>Field 1</th>
            <th>Field 2</th>
            <th>Field 3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Name</td>
            <td>Roll Number</td>
            <td> Subject<br></td>
        </tr>
        <tr>
            <td>Aditya</td>
            <td> 12</td>
            <td> Python<br></td>
        </tr>
        <tr>
            <td>Sam</td>
            <td> 23</td>
            <td> Java<br></td>
        </tr>
        <tr>
            <td>Chris</td>
            <td> 11</td>
            <td> C++<br></td>
        </tr>
        <tr>
            <td>Joel</td>
            <td> 10</td>
            <td> JavaScript<br></td>
        </tr>
        <tr>
            <td>Mayank</td>
            <td> 5</td>
            <td> Typescript</td>
        </tr>
    </tbody>
</table>

Conclusion

In this article, we have discussed how to convert a csv file to an HTML file in python. To know more about python programming, you can read this article on list comprehension in python. You might also like this article on dictionary comprehension in python.

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Basics Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup bitly Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehensions in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Pandas Append Row to DataFrame
  • Convert String to DataFrame in Python
  • Pandas DataFrame to List in Python
  • Solved: Dataframe Constructor Not Properly Called Error in Pandas
  • Overwrite a File in Python

Copyright © 2012–2023 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us