Jenveloper
Jenveloper

Reputation: 45

Create HTML Table with multiple python lists

I have three lists and would like to write them into a html file to create a table.

My lists are: host, ip, sshkey

I already tried:

with open("index.html", "a") as file:
    for line in host:
        file.write("<tr><td>" + line + "</td><td>" + ip + " </td><td> + sshkey + "</td>"
file.close() 

I got the error:

TypeError: cannot concatenate 'str' and 'list' objects

And when I try:

  file.write("<tr><td>" + line + "</td><td>" + ip[0] + " </td><td> + sshkey[0] + "</td>"

I get this:

Hostname1 IP1 SSHkey1
Hostname2 IP1 SSHkey1
Hostname3 IP1 SSHkey1

But I want this outcome:

Hostname1 IP1 SSHkey1
Hostname2 IP2 SSHkey2
Hostname3 IP3 SSHkey3

Upvotes: 0

Views: 545

Answers (2)

M. Fatih
M. Fatih

Reputation: 115

int i=0;
with open("index.html", "a") as file:
for line in host:
    file.write("<tr><td>" + line + "</td><td>" + ip[i] + "</td><td>" + sshkey[0] + "</td>");
    i++;
file.close() 

Upvotes: 0

Sunny Patel
Sunny Patel

Reputation: 8076

It's because you're iterating over one list when doing for line in host:.

You can use zip() to iterate through all of the lists simultaneously.

with open("index.html", "a") as file:
    for h, i, k in zip(host, ip, sshkey):
        file.write("<tr><td>" + h + "</td><td>" + i + "</td><td>" + k + "</td>")

Also, you had a few syntax errors in your code, which I updated. Missing quotes, closing parenthesis, and a redundant file close which happens automagically utilizing the with statement

Upvotes: 1

Related Questions