accepting file path or file object?

andrea crotti andrea.crotti.0 at
Mon Nov 5 11:54:08 CET 2012

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)
        fobj = filepath_obj

    for line in fobj:
        if, 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 is the caller that has to make sure to close the file

So I'm thinking if it's not just worth to skip the support for file
objects and only use the filenames, which seems a more robust and
consistent choice..

Any comment/suggestions about this?

More information about the Python-list mailing list