Welcome folks today in this blog post we will be exporting csv
file to html5
table and saving it as html
file inside the root directory in command line using csv
module. All the full source code of the application is shown below.
Get Started
In order to get started you need to make an app.py
file and copy paste the following code
app.py
1 2 3 4 5 |
import csv from html import escape csv_file = open('output.csv', 'r') csv_reader = csv.reader(csv_file) |
As you can see we are importing the csv
module and then we are importing the html
module from that we are importing the escape
method and then we are loading the input
csv file called output.csv
in read mode. And then we are reading the content of the csv
file using the reader()
method.
Writing the Contents inside HTML File
Now guys we will be opening the html file
using the open()
method as shown below
1 2 3 4 5 6 7 8 9 10 11 12 |
html_file = open('file.html', 'w') html_file.write('<table>') for row in csv_reader: html_file.write('<tr>') for cell in row: html_file.write(f'<td>{escape(cell)}</td>') html_file.write('</tr>') html_file.write('</table>') csv_file.close() html_file.close() |
As you can see we are using the write()
method to write the html
inside the file. And for this we are using the for
loop to iterate over all the contents present inside the csv
file and converting it to the table
rows and data. For escaping certain characters and entities
we are using the escape
method from the html module.
Now before running this python script you need to create the output.csv
file inside the root directory as shown below
output.csv
1 2 3 4 5 |
Name,Age,Country Alice,25,USA Bob,30,Canada Claire,35,UK David,40,Australia |
Now if you execute the python
script inside the command line you will see the file.html
will be created as shown below
python app.py