Re: accepting file path or file object?

2012-11-05 Thread Peter Otten
andrea crotti wrote: Quite often I find convenient to get a filename or a file object as argument of a function, and do something as below: def grep_file(regexp, filepath_obj): Check if the given text is found in any of the file lines, take a path to a file or an opened file object

Re: accepting file path or file object?

2012-11-05 Thread andrea crotti
2012/11/5 Peter Otten __pete...@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:

Re: accepting file path or file object?

2012-11-05 Thread Ulrich Eckhardt
Am 05.11.2012 11:54, schrieb andrea crotti: Quite often I find convenient to get a filename or a file object as argument of a function, and do something as below: def grep_file(regexp, filepath_obj): Check if the given text is found in any of the file lines, take a path to a file or

Re: accepting file path or file object?

2012-11-05 Thread Peter Otten
andrea crotti wrote: 2012/11/5 Peter Otten __pete...@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:

Re: accepting file path or file object?

2012-11-05 Thread Grant Edwards
On 2012-11-05, andrea crotti andrea.crott...@gmail.com wrote: Quite often I find convenient to get a filename or a file object as argument of a function, and do something as below: def grep_file(regexp, filepath_obj): [...] if isinstance(filepath_obj, basestring): fobj =

Re: accepting file path or file object?

2012-11-05 Thread Terry Reedy
On 11/5/2012 5:54 AM, andrea crotti wrote: Quite often I find convenient to get a filename or a file object as argument of a function, and do something as below: def grep_file(regexp, filepath_obj): Check if the given text is found in any of the file lines, take a path to a file or an

Re: accepting file path or file object?

2012-11-05 Thread Cameron Simpson
On 05Nov2012 10:54, andrea crotti andrea.crott...@gmail.com wrote: | Quite often I find convenient to get a filename or a file object as | argument of a function, and do something as below: I tend to do this: def f(fp): if isinstance(fp, str): with open(fp) as subfp: return