Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #32769 > unrolled thread

Re: accepting file path or file object?

Started byPeter Otten <__peter__@web.de>
First post2012-11-05 14:47 +0100
Last post2012-11-05 14:47 +0100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: accepting file path or file object? Peter Otten <__peter__@web.de> - 2012-11-05 14:47 +0100

#32769 — Re: accepting file path or file object?

FromPeter Otten <__peter__@web.de>
Date2012-11-05 14:47 +0100
SubjectRe: accepting file path or file object?
Message-ID<mailman.3282.1352123213.27098.python-list@python.org>
andrea crotti wrote:

> 2012/11/5 Peter Otten <__peter__@web.de>:
>> 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.

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web