Sandra-24 wrote: > 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)?
Both! Usually, the files will probably be closed *if* you are using CPython. However, there is absolutely no guarantee of this behavior. For example, Jython uses a different garbage collection scheme, and the files will *not* close immediately. Future versions of CPython may have different behavior, too. > 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? Just keep doing what you are doing, please. -- Robert Kern [EMAIL PROTECTED] "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list