Perl file::find module equivalent in Python?

Skip Montanaro skip at pobox.com
Thu Nov 6 00:01:19 CET 2003


    Greg> Hi. Does anyone know if there's an equivalent of Perl's file::find
    Greg> module in Python? It traverses a directory. I've googled
    Greg> extensively and checked this newsgroup and can't find anything
    Greg> like it for Python.

I've never used file::find, but from your short description ("traverses a
directory"), I suspect you're looking for os.listdir, os.path.walk or
perhaps glob.glob:

    listdir(...)
        listdir(path) -> list_of_strings

        Return a list containing the names of the entries in the directory.

                path: path of directory to list

        The list is in arbitrary order.  It does not include the special
        entries '.' and '..' even if they are present in the directory.

    walk(top, func, arg)
        Directory tree walk with callback function.

        For each directory in the directory tree rooted at top (including top
        itself, but excluding '.' and '..'), call func(arg, dirname, fnames).
        dirname is the name of the directory, and fnames a list of the names of
        the files and subdirectories in dirname (excluding '.' and '..').  func
        may modify the fnames list in-place (e.g. via del or slice assignment),
        and walk will only recurse into the subdirectories whose names remain in
        fnames; this can be used to implement a filter, or to impose a specific
        order of visiting.  No semantics are defined for, or required of, arg,
        beyond that arg is always passed to func.  It can be used, e.g., to pass
        a filename pattern, or a mutable object designed to accumulate
        statistics.  Passing None for arg is common.

    glob(pathname)
        Return a list of paths matching a pathname pattern.

        The pattern may contain simple shell-style wildcards a la fnmatch.

Skip





More information about the Python-list mailing list