Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: accepting file path or file object?

Reply
Thread Tools

Re: accepting file path or file object?

 
 
Terry Reedy
Guest
Posts: n/a
 
      11-05-2012
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

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: accepting file path or file object? Cameron Simpson Python 0 11-05-2012 09:58 PM
accepting file path or file object? andrea crotti Python 2 11-05-2012 03:05 PM
Re: accepting file path or file object? Peter Otten Python 0 11-05-2012 01:47 PM
Re: accepting file path or file object? Peter Otten Python 0 11-05-2012 11:49 AM
When did Windows start accepting forward slash as a path separator? Stephen Ferg Python 30 09-30-2003 04:22 AM



Advertisments