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
2 Answers 2
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
answered Apr 11, 2018 at 14:36
Sunny Patel
8,0982 gold badges35 silver badges47 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Jenveloper
Thank you very much! I'm still a beginner with python so this really helped a lot! :) Also I feel like an idiot for not copying my code correctly.. so yeah thanks for fixing my syntax errors. ^^'
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()
Darkstarone
4,7408 gold badges40 silver badges76 bronze badges
Comments
default
file.write("<tr><td>" + line + "</td><td>" + ip + " </td><td>" + sshkey + "</td>").sshkeywhich will change its value and you will get the desired result.