Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   Re: accepting file path or file object? (http://www.velocityreviews.com/forums/t954224-re-accepting-file-path-or-file-object.html)

Terry Reedy 11-05-2012 06:30 PM

Re: accepting file path or file object?
 
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 opened file object
> """
> if isinstance(filepath_obj, basestring):
> fobj = open(filepath_obj)
> else:
> fobj = filepath_obj
>
> for line in fobj:
> if re.search(regexp, line):
> return True
>
> return False
>
>
> This makes it also more convenient to unit-test, since I can just pass
> a StringIO. But then there are other problems, for example if I pass
> a file object [it] is the caller that has to make sure to close the file
> handle..


Which is as it should be. The caller should (normally) call your
function within a with statement or might want to do other operations on
the file before or after passing it to your grep_file.

--
Terry Jan Reedy



All times are GMT. The time now is 11:06 AM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.