Opening files without closing them

Sandra-24 sandravandale at yahoo.com
Sun Mar 5 23:33:22 CET 2006


I was reading over some python code recently, and I saw something like
this:

contents = open(file).read()

And of course you can also do:

open(file, "w").write(obj)

Why do they no close the files? Is this sloppy programming or is the
file automatically closed when the reference is destroyed (after this
line)? I usually use:

try:
  f = open(file)
  contents = f.read()
finally:
  f.close()

But now I am wondering if that is the same thing. Which method would
you rather use? Why?

Thanks,
Sandra




More information about the Python-list mailing list