question about file handling with "with"
__peter__ at web.de
Wed Mar 28 11:59:20 CEST 2012
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:
as roughly equivalent to
f = open(...)
See the "specification" section of
for the gory details.
More information about the Python-list