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


Groups > comp.lang.python > #32769

Re: accepting file path or file object?

From Peter Otten <__peter__@web.de>
Subject Re: accepting file path or file object?
Date 2012-11-05 14:47 +0100
Organization None
References <CAF_E5JYQd5aPnjtpjiHVBpsro-85pV-4zQA9oaNdPUkhOkAZ9g@mail.gmail.com> <k7892k$g9d$1@ger.gmane.org> <CAF_E5JYZydsjD=BF3HsvdAVUf31z1f2VFzq9dByE8J2xrofGdw@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.3282.1352123213.27098.python-list@python.org> (permalink)

Show all headers | View raw


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.

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

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

csiph-web