question about file handling with "with"

Peter Otten __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:
   # 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.




More information about the Python-list mailing list