Path: csiph.com!usenet.pasdenom.info!weretis.net!feeder4.news.weretis.net!news.musoftware.de!wum.musoftware.de!newsfeed.kamp.net!newsfeed.kamp.net!news.qsc.de!zen.net.uk!hamilton.zen.co.uk!reader01.nrc01.news.zen.net.uk.POSTED!not-for-mail From: Nobody Subject: Re: question about file handling with "with" Date: Thu, 29 Mar 2012 17:25:38 +0100 User-Agent: Pan/0.14.2 (This is not a psychotic episode. It's a cleansing moment of clarity.) Message-Id: Newsgroups: comp.lang.python References: MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Lines: 17 Organization: Zen Internet NNTP-Posting-Host: 94bbf63a.news.zen.co.uk X-Trace: DXC=AEh:kI_gi3PZhEmRS@T;C_a0UP_O8AJo\=dR0\ckLKGPWeZ<[7LZNRVjhSaoW2RCG[M2Z^cWRFGA[6342M2]WEFP X-Complaints-To: abuse@zen.co.uk Xref: csiph.com comp.lang.python:22347 On Wed, 28 Mar 2012 11:31:21 +0200, Jabba Laci wrote: > Is the following function correct? Is the input file closed in order? > > def read_data_file(self): > with open(self.data_file) as f: > return json.loads(f.read()) Yes. The whole point of being able to use a file as a context manager is so that the file will be closed immediately upon leaving the with statement, whether by falling off the end, "return", an exception, or whatever. IOW, it's like calling .close() immediately after the "with" block, only more so, i.e. it will also handle cases that an explicit .close() misses.