Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #22271 > unrolled thread

Re: question about file handling with "with"

Started byPeter Otten <__peter__@web.de>
First post2012-03-28 11:59 +0200
Last post2012-03-28 11:59 +0200
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: question about file handling with "with" Peter Otten <__peter__@web.de> - 2012-03-28 11:59 +0200

#22271 — Re: question about file handling with "with"

FromPeter Otten <__peter__@web.de>
Date2012-03-28 11:59 +0200
SubjectRe: question about file handling with "with"
Message-ID<mailman.1068.1332928726.3037.python-list@python.org>
Jabba Laci wrote:

> Is the following function correct? 

Yes, though I'd use json.load(f) instead of json.loads().

> Is the input file closed in order?
> 
> def read_data_file(self):
>     with open(self.data_file) as f:
>         return json.loads(f.read())


The file will be closed when the with-block is left. That is before 
read_data_file() returns, even in a Python implementation that doesn't use 
ref-counting. Think of

with open(...) as f:
   # whatever

as roughly equivalent to

f = open(...)
try:
    # whatever
finally:
    f.close()

See the "specification" section of

http://www.python.org/dev/peps/pep-0343/

for the gory details.

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web