简体   繁体   中英

How do I print a list in python to a file

I have a list of data with multiple rows that I have read from an excel file I then read it in to a list. Now, I would like to print this list to another text file and save it and then print out html to another file. Then I would like to make a html file so I can make a table so that it has 4 rows and each row would contain one cell of data.

Note: I am using python 3.

I have tried this so far but it does not seem to work.

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)

Your code list initialization translates to:

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

but you need to make a list of lists:

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

Next, you can write your data to file:

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

Once you get your list correctly assembled as noted in the above answer, you can do the output part as mentioned, or like this:

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

Here is a hint on an easy way to do the HTML output portion in the same manner as the CSV portion.

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

There is also a python csv library that helps with more in-depth CSV needs: http://docs.python.org/3.3/library/csv.html

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

The table style comes from here . :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM