question about file handling with "with"

Discussion in 'Python' started by Jabba Laci, Mar 28, 2012.

  1. Jabba Laci

    Jabba Laci Guest

    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
    Jabba Laci, Mar 28, 2012
    #1
    1. Advertising

  2. Jabba Laci

    Nobody Guest

    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.
    Nobody, Mar 29, 2012
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Sean W. Quinn
    Replies:
    1
    Views:
    353
    Gianni Mariani
    Dec 1, 2003
  2. uwb
    Replies:
    4
    Views:
    351
  3. Mark Tarver
    Replies:
    22
    Views:
    1,279
    J Kenneth King
    Apr 26, 2009
  4. Peter
    Replies:
    34
    Views:
    1,916
    James Kanze
    Oct 17, 2009
  5. Iñaki Baz Castillo
    Replies:
    1
    Views:
    175
    Iñaki Baz Castillo
    Apr 15, 2008
Loading...

Share This Page