[Tutor] Is there a way to use "with" across suite boundaries?
Peter Otten
__peter__ at web.de
Sat May 23 08:55:06 CEST 2015
Jim Mooney Py3.4.3winXP wrote:
> '''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?
Something else must have gone wrong as
def make_lines():
with open('co2-sample.csv') as co2:
with open('output.html', 'w') as ht:
linelist = []
print(htbegin, file=ht)
for line in co2:
newlist = line.rsplit(',', 5)
for token in newlist:
linelist.append(token.strip('"'))
linelist[-1] = linelist[-1].strip()
fprint(linelist, ht)
linelist = []
print(htend, file=ht)
should run without error. Also possible:
with open('co2-sample.csv') as co2, open('output.html', 'w') as ht:
...
But may I suggest that you delegate parsing the CSV to the standard library?
Then you can write
import csv
def make_lines():
with open('co2-sample.csv') as co2:
rows = csv.reader(co2)
with open('output.html', 'w') as ht:
print(htbegin, file=ht)
for linelist in rows:
fprint(linelist, ht)
print(htend, file=ht)
> 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()
More information about the Tutor
mailing list