question about file handling with "with"

J

Jabba Laci

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
 
N

Nobody

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top