My first Python program

Chris Kaynor ckaynor at zindagigames.com
Wed Oct 13 15:30:13 EDT 2010


On Wed, Oct 13, 2010 at 12:12 PM, Seebs <usenet-nospam at seebs.net> wrote:

> On 2010-10-13, Jonas H. <jonas at lophus.org> wrote:
> > Not really. Files will be closed when the garbage collector collects the
> > file object, but you can't be sure the GC will run within the next N
> > seconds/instructions or something like that. So you should *always* make
> > sure to close files after using them. That's what context managers were
> > introduced for.
>
> >      with open('foobar') as fileobject:
> >          do_something_with(fileobject)
>
> That makes sense.  I don't think it'd quite work in this case, because I
> want to open several files all at once, do a ton of work that populates
> them with files, and then close them all.
>
> This is a nice idiom, though.  In C, I've been sort of missing that idiom,
> which I first encountered in Ruby.  (I mean, spelled differently, but the
> same basic thing.)
>

For opening multiple files, you can either nest the with statements:
with open('foobar1') as foobar1:
   dosomethingwithfoobar1()
   with open('foobar2') as foobar2:
      dosomethingwithfoobar2()
      dosomethingelsewithfoobar1()

or you can use the contextlib module to nest them in one line:
import contextlib
with contextlib.nested(open('foobar1'), open('foobar2')) as (foobar1,
foobar2):
    dosomethingwithfoobar1and2()


> -s
> --
> Copyright 2010, all wrongs reversed.  Peter Seebach /
> usenet-nospam at seebs.net
> http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
> http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
> I am not speaking for my employer, although they do rent some of my
> opinions.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20101013/780ecea7/attachment-0002.html>


More information about the Python-list mailing list