question about file handling with "with"

Peter Otten __peter__ at
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(

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(...)
    # whatever

See the "specification" section of

for the gory details.

More information about the Python-list mailing list