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


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

Re: accepting file path or file object?

Started byandrea crotti <andrea.crotti.0@gmail.com>
First post2012-11-05 13:16 +0000
Last post2012-11-05 13:16 +0000
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? andrea crotti <andrea.crotti.0@gmail.com> - 2012-11-05 13:16 +0000

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

Fromandrea crotti <andrea.crotti.0@gmail.com>
Date2012-11-05 13:16 +0000
SubjectRe: accepting file path or file object?
Message-ID<mailman.3281.1352121410.27098.python-list@python.org>
2012/11/5 Peter Otten <__peter__@web.de>:
> I sometimes do something like this:
>
> $ cat xopen.py
> import re
> import sys
> from contextlib import contextmanager
>
> @contextmanager
> def xopen(file=None, mode="r"):
>     if hasattr(file, "read"):
>         yield file
>     elif file == "-":
>         if "w" in mode:
>             yield sys.stdout
>         else:
>             yield sys.stdin
>     else:
>         with open(file, mode) as f:
>             yield f
>
> def grep(stream, regex):
>     search = re.compile(regex).search
>     return any(search(line) for line in stream)
>
> if len(sys.argv) == 1:
>     print grep(["alpha", "beta", "gamma"], "gamma")
> else:
>     with xopen(sys.argv[1]) as f:
>         print grep(f, sys.argv[2])
> $ python xopen.py
> True
> $ echo 'alpha beta gamma' | python xopen.py - gamma
> True
> $ echo 'alpha beta gamma' | python xopen.py - delta
> False
> $ python xopen.py xopen.py context
> True
> $ python xopen.py xopen.py gamma
> True
> $ python xopen.py xopen.py delta
> False
> $
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list

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..

[toc] | [standalone]


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


csiph-web