【问题标题】:How do I print a list in python to a file如何将python中的列表打印到文件中
【发布时间】:2012-11-25 16:21:47
【问题描述】:

我有一个包含多行的数据列表,我从一个 excel 文件中读取了这些数据,然后将其读入一个列表。 现在,我想将此列表打印到另一个文本文件并保存,然后将 html 打印到另一个文件。 然后我想制作一个 html 文件,这样我就可以制作一个表格,让它有 4 行,每行包含一个数据单元格。

注意:我使用的是 python 3。

到目前为止我已经尝试过了,但它似乎不起作用。

data = ['Course name', 'Course Type', 'Tutor']
       ['English',    , 'Languages' , 'Mr A']
       ['Geography'   , 'Humanities', 'Mr B']
       ['Civil Engineering' , 'Engineering', 'Mr C']

f = open("SomeData.csv", 'w')
for row in mylist:
    print(row,file=f)

【问题讨论】:

  • 您将data 显示为一个列表,一些“裸”列表,但在循环中使用mylist
  • csv 模块写入 csv 文件是个好主意。那么您就不必担心其中一个字段是否包含需要转义的字符。

标签: python python-3.x


【解决方案1】:

您的代码列表初始化转换为:

data = ['Course name', 'Course Type', 'Tutor']

['English',    , 'Languages' , 'Mr A']             # Just a statement
['Geography'   , 'Humanities', 'Mr B']             # Just a statement
['Civil Engineering' , 'Engineering', 'Mr C']      # Just a statement

但你需要列出一个列表:

data = [
    ['Course name', 'Course Type', 'Tutor'],
    ['English', 'Languages' , 'Mr A'],
    ['Geography', 'Humanities', 'Mr B'],
    ['Civil Engineering', 'Engineering', 'Mr C']
]

接下来,您可以将数据写入文件:

f = open("output.txt", "w")
for row in data:
    print(", ".join(row), file=f)
f.close()

【讨论】:

  • 您可以通过执行以下操作避免内循环:print(", ".join(row), file=f),并且您可以删除尾随打印。
  • 我已决定添加学生 ID,但我收到一条错误消息,提示列表索引必须是整数而不是元组。 data = [ ['学号','课程名称', '课程类型', '导师'], ['12345','英语', '语言' , 'A先生'], ['34598','地理','人文','B先生'],['23976','土木工程','工程','C先生']]
  • 如果那真的是 OP 的代码,它不应该引发IndentationError吗?
  • @gg.kaspersky,我试过了,打开的时候文件里面没有数据。
  • 您是否尝试在 python 中关闭文件之前打开它? (虽然它还在运行?)
【解决方案2】:

按照上述答案正确组装列表后,您可以按照所述执行输出部分,或者像这样:

f = open("SomeData.csv", 'w')
for row in data:
    f.write(",".join(row)+",")
f.close()

这里提示了一种以与 CSV 部分相同的方式执行 HTML 输出部分的简单方法。

f = open("output.html", 'w')
f.write("<html><table>")
for row in data:
    f.write("<tr><td>"+"</td><td>".join(row)+"</td></tr>")
f.write("</table></html>")
f.close()

还有一个 python csv 库可以帮助满足更深入的 CSV 需求:http://docs.python.org/3.3/library/csv.html

【讨论】:

  • 谢谢 - 我试过了,但是当加载页面时,它不是以表格格式显示,而是彼此相邻显示,没有空格。
  • 您仍然需要标签才能使其成为合法文档,即 ...
  • 我不认为 "&lt;tr&gt;&lt;td&gt;"+"&lt;/td&gt;&lt;td&gt;".join(row)+"&lt;/td&gt;&lt;/tr&gt;" 能满足您的期望......和需要。
【解决方案3】:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import csv

class CoolFileWriter:
    """reads a csv file and writes a text or html file"""
    def __init__(self, csv_file, txt_out='out.txt', html_out='out.html'):
        self.csv_file = csv_file
        self.txt_out = txt_out
        self.html_out = html_out
        self.content = []

    def read_csv(self):
        with open(self.csv_file, newline='') as f:
            reader = csv.reader(f)
            for row in reader:
                self.content.append(row)

    def write_txt(self):
        f = open(self.txt_out, 'w')
        for row in self.content:
            f.write(', '.join(row) + '\n')
        f.close()

    def write_html(self):
        html_pre="""
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Table Data</title>
<style>
#newspaper-a
{
    font-family: "Lucida Sans Unicode", "Lucida Grande", Sans-Serif;
    font-size: 12px;
    margin: 45px;
    width: 480px;
    text-align: left;
    border-collapse: collapse;
    border: 1px solid #69c;
}
#newspaper-a th
{
    padding: 12px 17px 12px 17px;
    font-weight: normal;
    font-size: 14px;
    color: #039;
    border-bottom: 1px dashed #69c;
}
#newspaper-a td
{
    padding: 7px 17px 7px 17px;
    color: #669;
}
</style>
</head>
<body>
<table id="newspaper-a">
"""
        html_post="""
</table>
</body>
</html>
"""
        f = open(self.html_out, 'w')
        f.write(html_pre)
        th=True
        for row in self.content:
            if (th):
                f.write("<tr>\n\t<th>"+"</th>\n\t<th>".join(row)+"</th>\n</tr>\n")
                th=False
            else:
                f.write("<tr>\n\t<td>"+"</td>\n\t<td>".join(row)+"</td>\n</tr>\n")
        f.write(html_post)
        f.close()

f = CoolFileWriter('excel.csv', 'data.txt', 'data.html')

f.read_csv()
f.write_txt()
f.write_html()

表格样式来自here。 :-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-26
    • 2013-08-10
    • 2013-05-16
    • 1970-01-01
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    • 2018-06-02
    相关资源
    最近更新 更多