Converting CSV to HTML table in Python
In this post, we are going to see how to convert a CSV file to an HTML table in Python. Here, we will discuss two methods that are available in Python.
- Using pandas.
- Using PrettyTable.
- Expansion: Comma Separated Value file.
- To exchange data between applications, a CSV file can be used.
- It is a text file that has information that is separated by commas.
- Extension: .csv
Method 1: Using pandas
Among the 2 methods, the simplest one is using pandas. Pandas is very suitable to work with data that is in structural form. It is fast and provides expressive data structures. We are going to show you how we can use the Pandas library to convert a CSV into an HTML table.
pip install pandas
Below is the CSV file,
- First, we imported the pandas library.
- Then we read the CSV file using the read_csv() method.
- Syntax: pandas.read_csv(csv_file)
- After that, our CSV file is converted into HTML file using to_html() method.
- Syntax: file.to_html(filename)
Now, we have a look at the program.
import pandas file = pandas.read_csv("Student.csv") file.to_html("StudentTable.html")
After executing the above code, our HTML table will look like below,
Method 2: Using PrettyTable
When there is a need to create quick and simple ASCII tables, PrettyTable library can be used.
pip install PrettyTable
Let’s look into our program.
- We have imported the PrettyTable library initially.
- Then we opened the CSV file in reading mode using open() method.
- Syntax: open(filename,mode)
- After that, we read all the lines from the CSV files using readlines() method.
- Syntax: file.readlines()
- We assigned file to the head variable. Because file contains the headings present in the CSV file.
- Then we used the split() method which is used to separate the given string based on the separator given.
- Synatx: string.split(separator)
- We added rows to the table using the add_row() method.
- Syntax: table.add_row(data)
- Then, get_html_string() method is used to return the string representation of HTML table’s version.
- Syntax: table.get_html_string()
- Finally, we wrote the entire data into the final HTML file using the file.write() method
from prettytable import PrettyTable file = open("Student.csv", 'r') file = file.readlines() head = file head = head.split(',') #for headings table = PrettyTable([head, head,head]) for i in range(1, len(file)) : table.add_row(file[i].split(',')) htmlCode = table.get_html_string() final_htmlFile = open('StudentTable2.html', 'w') final_htmlFile=final_htmlFile.write(htmlCode)
After the execution of the code, our output will look like below.
I hope that this tutorial has taught you something new and useful.