I am trying to write a HTML file using python, and I want to print in .html a nested list.
I have written this, but I donĀ“t have any idea about how to doit good.
words = [['Hi'], ['From'], ['Python']] with open('mypage.html', 'w') as myFile: myFile.write('<html>') myFile.write('<body>') myFile.write('<h1>---------------------------</h1>') for i in range(len(words)): myFile.write('<tr><td>'(words[i])'</td></tr>') myFile.write('</body>') myFile.write('</html>')
In .html I want to print the nested list in a table in this similar format:
<body> <table> <tr> <td>Hi</td> </tr> <tr> <td>From</td> </tr> <tr> <td>Python</td> </tr> </table> </body>
Advertisement
Answer
words = [['Hi'], ['From'], ['Python']] with open('mypage.html', 'w') as myFile: myFile.write('<html>') myFile.write('<body>') myFile.write('<h1>---------------------------</h1>') # 2-depth string data to 1-depth words = [word_str for inner in words for word_str in inner] # use fstring to build string <table> for word in words: myFile.write(f'<tr><td>{word}</td></tr>') </table> myFile.write('</body>') myFile.write('</html>')
I tried to edit the accepted answer but I were not available but, you just have to add <table> and </table>