[CentralOH] Files and context manager

Brian Costlow brian.costlow at gmail.com
Wed Mar 10 23:34:27 CET 2010


Hi Mark,

Yes. Although you can get that same level of safety without them.

The way contexts are used with file objects in python is they are a shortcut for

try:
    x = open(filename,'rb').read()
    # do stuff with x
finally:
    x.close()

If you need to do error handling though, you still need to catch
exceptions. But if you are catching them farther upstream you don't
need to clutter your code with try blocks just for the file
open/read/close idiom.

Not sure what you mean by a good idea. If you have code in a bunch of
places in an app that opens and reads files by filename, of course
putting that in a function is a good idea. But if you are asking, is
it okay to just read a (potentially large) file into memory using
read(), I do it all the time for files in the 5-35 mb range in an app
that checksums images.




On Wed, Mar 10, 2010 at 3:39 PM, Mark Erbaugh <mark at microenh.com> wrote:
>
>
> A common idiom with older versions of Python is:
>
> x = open(filename,'rb').read()
>
> With context managers in 2.6+ you could say:
>
> with open(filename,'rb') as f:
> x = f.read()
>
> Is the later safer in that it explicitly will call close() whereas the
> former depends on the file destructor to close the file?
>
>
> I forgot the second half of my question.
> Is a function like:
> def getData(filename):
> with open(filename,'rb') as f:
>              return f.read()
>
> a good idea?
> _______________________________________________
> CentralOH mailing list
> CentralOH at python.org
> http://mail.python.org/mailman/listinfo/centraloh
>
>


More information about the CentralOH mailing list