'''I was using with open...:, but I'm printing a header in one function,
calling a looping
function to print detail lines, then returning to the calling function to
print
the footer. But that didn't work since the with statement only seems to work
with the lexical suite and the file wasn't open in the detail print
function. Is there
a way around this, other than passing the file as I have here? Also, is it a
good idea to pass a file handle like that or is there a better way?

Using the below csv file  co2-sample.csv  to print a simple HTML table
(header omitted)
Since this is a file there are enclosing single quotes not visible:

"ANTIGUA AND BARBUDA",0,0,0,0,0
"ARGENTINA",37,35,33,36,39
"BAHAMAS, THE",1,1,1,1,1
"BAHRAIN",5,6,6,6,6
"SPANISH INQUISITION, THE, SILLY",10,33,14,2,8

Program follows (py3.4, winxp):'''

htbegin = '''
<html>
<head>
<title>htest</title>
<style>
table, td {border:2px solid black; border-collapse:collapse;}
td {padding:3px; background-color:pink;
text-align:right;font-family:verdana;}
td.l {text-align:left}
</style>

</head>
<body>
<table>
'''

htend = '''
</table>
</body>
</html>
'''

def make_lines():
    co2 = open('co2-sample.csv')
    ht = open('output.html', 'w')
    linelist = []
    print(htbegin, file=ht)
    for line in co2:
        newlist = line.rsplit(',', 5) # ending is regular so split it out
first
        for token in newlist:         # since split char inside quotes for
nation is problematic
            linelist.append(token.strip('"')) # get rid of extra quotes
            linelist[-1] = linelist[-1].strip()
        fprint(linelist, ht)
        linelist = []
    co2.close()
    print(htend, file=ht)
    ht.close()


def fprint(linelist, ht):
    # size formatting irrelevant for HTML
    formatted_string = "<td
class=l>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td>".format(*linelist)
    print(formatted_string, file=ht)
    print('</tr>', file=ht)


if __name__ == "__main__":
    make_lines()






-- 
Jim
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to