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


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

question about file handling with "with"

Started byJabba Laci <jabba.laci@gmail.com>
First post2012-03-28 11:31 +0200
Last post2012-03-29 17:25 +0100
Articles 2 — 2 participants

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


Contents

  question about file handling with "with" Jabba Laci <jabba.laci@gmail.com> - 2012-03-28 11:31 +0200
    Re: question about file handling with "with" Nobody <nobody@nowhere.com> - 2012-03-29 17:25 +0100

#22269 — question about file handling with "with"

FromJabba Laci <jabba.laci@gmail.com>
Date2012-03-28 11:31 +0200
Subjectquestion about file handling with "with"
Message-ID<mailman.1067.1332927106.3037.python-list@python.org>
Hi,

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())

Thanks,

Laszlo

[toc] | [next] | [standalone]


#22347

FromNobody <nobody@nowhere.com>
Date2012-03-29 17:25 +0100
Message-ID<pan.2012.03.29.16.25.52.82000@nowhere.com>
In reply to#22269
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.

[toc] | [prev] | [standalone]


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


csiph-web