accepting file path or file object?

andrea crotti andrea.crotti.0 at gmail.com
Mon Nov 5 05:54:08 EST 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)
    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 is the caller that has to make sure to close the file
handle..

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