[Tutor] Is there a way to use "with" across suite boundaries?

Peter Otten __peter__ at web.de
Sat May 23 11:52:48 CEST 2015


Jim Mooney Py3.4.3winXP wrote:

> 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?

Not necessarily better, but instead of passing around the file you can 
rewrite your code to use generators:

import csv


def make_lines():
    with open('co2-sample.csv') as co2:
        yield htbegin
        for linelist in csv.reader(co2):
            yield from fprint(linelist)
        yield htend


def fprint(linelist):
    yield ("<td class=l>{}</td><td>{}</td><td>{}</td>"
           "<td>{}</td><td>{}</td><td>{}</td>\n").format(*linelist)
    yield '</tr>\n'


if __name__ == "__main__":
    with open('output.html', 'w') as ht:
        ht.writelines(make_lines())


Python versions before 3.3 don't understand

yield from fprint(linelist)

You have to write

for s in fprint(linelist):
    yield s

instead.




More information about the Tutor mailing list