Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > question about file handling with "with"

Reply
Thread Tools

question about file handling with "with"

 
 
Jabba Laci
Guest
Posts: n/a
 
      03-28-2012
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
 
Reply With Quote
 
 
 
 
Nobody
Guest
Posts: n/a
 
      03-29-2012
On Wed, 28 Mar 2012 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.

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
signal handling and (structured) exception handling Peter C++ 34 10-17-2009 10:03 AM
python list handling and Lisp list handling Mark Tarver Python 22 04-26-2009 09:36 PM
Is faster handling hexadecimal values than handling chars? IƱaki Baz Castillo Ruby 1 04-15-2008 09:04 AM
file handling in a server (.py) file using xmlrpc uwb Python 4 07-08-2005 07:55 PM
General File Handling (Class Structure Preservation) Question Sean W. Quinn C++ 1 12-01-2003 02:58 AM



Advertisments
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57