[Tutor] Is there a way to use "with" across suite boundaries?
Cameron Simpson
cs at zip.com.au
Sat May 23 08:17:26 CEST 2015
On 22May2015 22:56, Jim Mooney Py3.4.3winXP <cybervigilante at gmail.com> 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?
It is just fine. Example:
with open("blah", "w") as blahfp:
print("header", file=blahfp)
print_details(blahfp, ...)
print("footer", file=blahfp)
def print_details(fp, blah_info):
... loop using blah_info to write data to "fp"
Cheers,
Cameron Simpson <cs at zip.com.au>
More information about the Tutor
mailing list