question about file handling with "with"

Nobody nobody at nowhere.com
Thu Mar 29 12:25:38 EDT 2012


On 2012年3月28日 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.


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /