0

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
  • Does this not produce some type of a syntax error? You're missing a closing bracket and a quote. I believe you want file.write("<tr><td>" + line + "</td><td>" + ip + " </td><td>" + sshkey + "</td>"). Commented Apr 11, 2018 at 14:35
  • You can add a count for sshkey which will change its value and you will get the desired result. Commented Apr 11, 2018 at 14:36

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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. ^^'
0
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() 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.