.csv to HTML Converter
This is a really simple but effective way to convert single column .csv files to HTML files.
Usage
Why would you use this? Well sometimes you may have a long list you want to render as a table on a website. It can be very time consuming to do this by hand, so this script does it automaticaly in the blink of an eye. I used it on this post to render the list of voices as a table.
Prerequisites
There are no prerequisites to install with this script.
How to use it
- Save the script below in the folder of your choice
- Rename the .csv file you want to convert as “input.csv” and save it in the same folder as the script
- Run the script
- The HTML file is saved as “output.html”
- If you want more than 2 columns, change “2” in the two places in the script indicated by comments
import csv
def csv_to_html(input_csv, output_html):
with open(input_csv, 'r') as file:
reader = csv.reader(file)
data = [row[0] for row in reader]
html_table = '<table>\n'
for i in range(0, len(data), 2): # Change "2" to the number of columns you require
html_table += '<tr>\n'
for j in range(2): # Change "2" to the number of columns you require
if i + j < len(data):
html_table += f'<td>{data[i + j]}</td>'
else:
html_table += '<td></td>' # Add empty cell if data is exhausted
html_table += '</tr>\n'
html_table += '</table>'
with open(output_html, 'w') as output_file:
output_file.write(html_table)
if __name__ == "__main__":
input_csv_file = "input.csv"
output_html_file = "output.html"
csv_to_html(input_csv_file, output_html_file)