File to dict
Neil Cerutti
horpner at yahoo.com
Fri Dec 7 11:14:59 EST 2007
More information about the Python-list mailing list
Fri Dec 7 11:14:59 EST 2007
- Previous message (by thread): File to dict
- Next message (by thread): File to dict
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On 2007-12-07, Duncan Booth <duncan.booth at invalid.invalid> wrote: > Neil Cerutti <horpner at yahoo.com> wrote: > >> On 2007-12-07, Duncan Booth <duncan.booth at invalid.invalid> 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
- Previous message (by thread): File to dict
- Next message (by thread): File to dict
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list