【问题标题】:Create HTML Table with multiple python lists使用多个 python 列表创建 HTML 表
【发布时间】:2018-09-21 12:02:11
【问题描述】:

我有三个列表,想将它们写入一个 html 文件以创建一个表。

我的清单是: 主机、ip、sshkey

我已经试过了:

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() 

我得到了错误:

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

当我尝试时:

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

我明白了:

Hostname1 IP1 SSHkey1
Hostname2 IP1 SSHkey1
Hostname3 IP1 SSHkey1

但我想要这样的结果:

Hostname1 IP1 SSHkey1
Hostname2 IP2 SSHkey2
Hostname3 IP3 SSHkey3

【问题讨论】:

  • 这不会产生某种类型的语法错误吗?您缺少右括号和引号。我相信你想要file.write("&lt;tr&gt;&lt;td&gt;" + line + "&lt;/td&gt;&lt;td&gt;" + ip + " &lt;/td&gt;&lt;td&gt;" + sshkey + "&lt;/td&gt;")。
  • 您可以为sshkey 添加一个计数,这将更改其值,您将获得所需的结果。

标签: python html list html-table


【解决方案1】:

这是因为您在执行for line in host: 时迭代了一个列表。

您可以使用zip() 同时遍历所有列表。

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>")

此外,您的代码中有一些语法错误,我已对其进行了更新。使用with 语句自动发生的缺少引号、右括号和冗余文件关闭

【讨论】:

  • 非常感谢!我仍然是 python 的初学者,所以这真的很有帮助! :) 另外,我觉得自己像个白痴,因为没有正确复制我的代码。所以是的,感谢您修复了我的语法错误。 ^^'
【解决方案2】:
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() 

【讨论】:

    猜你喜欢
    • 2014-04-06
    • 1970-01-01
    • 2019-03-17
    • 2020-09-15
    • 2014-08-28
    • 2014-01-28
    • 2022-06-27
    • 1970-01-01
    • 2014-08-26
    相关资源
    最近更新 更多