accepting file path or file object?

andrea crotti andrea.crotti.0 at gmail.com
Mon Nov 5 08:16:47 EST 2012


2012/11/5 Peter Otten <__peter__ at 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..



More information about the Python-list mailing list