Why going through all that complexity when you can simply use pandas.DataFrame.to_html?! It will write the html from the df for you in 1 line.