Re: accepting file path or file object?

Discussion in 'Python' started by Peter Otten, Nov 5, 2012.

  1. Peter Otten

    Peter Otten Guest

    andrea crotti wrote:

    > 2012/11/5 Peter Otten <>:
    >> I sometimes do something like this:


    >> @contextmanager
    >> def xopen(file=None, mode="r"):
    >> if hasattr(file, "read"):
    >> yield file

    elif file == "-" or file is None: # add file=None handling
    >> if "w" in mode:
    >> yield sys.stdout
    >> else:
    >> yield sys.stdin
    >> else:
    >> with open(file, mode) as f:
    >> yield f


    > That's nice thanks, there is still the problem of closing the file
    > handle but that's maybe not so important if it gets closed at
    > termination anyway..


    I think you misunderstood the behaviour of my context manager. The with-
    statement (the last two lines) in xopen() implicitly closes files that are
    opened by xopen().

    If you pass a file name the file will be closed:

    >>> with xopen("xopen.py") as f: pass

    ....
    >>> f.closed

    True

    However, if you pass an existing file it will not be closed:

    >>> import sys
    >>> from xopen import xopen
    >>> with xopen(sys.stdout) as f: pass

    ....
    >>> f.closed

    False

    That behaviour allows arbitrary nesting of with-statements

    fn = ...
    with xopen(fn) as f1:
    with xopen(f1) as f2:
    with xopen(f2) as f3:
    pass

    and the file may only be closed on the outermost level.
     
    Peter Otten, Nov 5, 2012
    #1
    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. Stephen Ferg
    Replies:
    30
    Views:
    958
    Andrew Dalke
    Sep 30, 2003
  2. andrea crotti

    accepting file path or file object?

    andrea crotti, Nov 5, 2012, in forum: Python
    Replies:
    2
    Views:
    276
    Grant Edwards
    Nov 5, 2012
  3. Peter Otten

    Re: accepting file path or file object?

    Peter Otten, Nov 5, 2012, in forum: Python
    Replies:
    0
    Views:
    238
    Peter Otten
    Nov 5, 2012
  4. Terry Reedy

    Re: accepting file path or file object?

    Terry Reedy, Nov 5, 2012, in forum: Python
    Replies:
    0
    Views:
    222
    Terry Reedy
    Nov 5, 2012
  5. Cameron Simpson

    Re: accepting file path or file object?

    Cameron Simpson, Nov 5, 2012, in forum: Python
    Replies:
    0
    Views:
    241
    Cameron Simpson
    Nov 5, 2012
Loading...

Share This Page