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


Groups > comp.lang.python > #22271

Re: question about file handling with "with"

From Peter Otten <__peter__@web.de>
Subject Re: question about file handling with "with"
Date 2012-03-28 11:59 +0200
Organization None
References <CAOuJsMm2CXh9RCSk_4-PyeaBR+N9gqkbP2=gSxXxHoEsD9mTZg@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.1068.1332928726.3037.python-list@python.org> (permalink)

Show all headers | View raw


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.

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

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

csiph-web