Re: accepting file path or file object?

Discussion in 'Python' started by Terry Reedy, Nov 5, 2012.

  1. Terry Reedy

    Terry Reedy Guest

    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
     
    Terry Reedy, Nov 5, 2012
    #1
    1. Advertisements

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Stephen Ferg
    Replies:
    30
    Views:
    986
    Andrew Dalke
    Sep 30, 2003
  2. andrea crotti

    accepting file path or file object?

    andrea crotti, Nov 5, 2012, in forum: Python
    Replies:
    2
    Views:
    292
    Grant Edwards
    Nov 5, 2012
  3. Peter Otten

    Re: accepting file path or file object?

    Peter Otten, Nov 5, 2012, in forum: Python
    Replies:
    0
    Views:
    252
    Peter Otten
    Nov 5, 2012
  4. Peter Otten

    Re: accepting file path or file object?

    Peter Otten, Nov 5, 2012, in forum: Python
    Replies:
    0
    Views:
    274
    Peter Otten
    Nov 5, 2012
  5. Cameron Simpson

    Re: accepting file path or file object?

    Cameron Simpson, Nov 5, 2012, in forum: Python
    Replies:
    0
    Views:
    250
    Cameron Simpson
    Nov 5, 2012
Loading...

Share This Page