On 2007-12-07, Duncan Booth <[EMAIL PROTECTED]> wrote: > Neil Cerutti <[EMAIL PROTECTED]> wrote: > >> On 2007-12-07, Duncan Booth <[EMAIL PROTECTED]> wrote: >>> from __future__ import with_statement >>> >>> def loaddomainowners(domain): >>> with open('/etc/virtual/domainowners','r') as infile: >> >> I've been thinking I have to use contextlib.closing for >> auto-closing files. Is that not so? >> > That is not so. > > Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> from __future__ import with_statement >>>> with open('diffs.txt') as f: > ... print len(list(f)) > ... > 40 >>>> f ><closed file 'diffs.txt', mode 'r' at 0x00AA0698>
Thanks. After seeing your answer I managed to find what I'd overlooked before, in the docs for file.close: As of Python 2.5, you can avoid having to call this method explicitly if you use the with statement. For example, the following code will automatically close f when the with block is exited: from __future__ import with_statement with open("hello.txt") as f: for line in f: print line -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list