如何将python中的列表打印到文件中

时间:2012-11-25 16:21:47

标签: python python-3.x

我有一个包含多行的数据列表,我已从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)

3 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分: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

答案 2 :(得分:1)

#!/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。 : - )