[Tutor] bash find equivalent in Python

tpc@csua.berkeley.edu tpc@csua.berkeley.edu
Thu Jul 10 19:31:01 2003


I am trying to index all html files within a document tree and so far I
have:

<code>
DIR = '/usr/local/apache2/htdocs'
myList = []
for f in os.listdir(DIR):
	path = os.path.join(DIR, f)
	if os.path.isfile(path) and f.endswith('.html'):
	        myList.append(path)
	elif os.path.isdir(path):
		os.chdir(path)
                for f in os.listdir(os.getcwd()):
		        path = os.path.join(os.getcwd(), f)
                        if os.path.isfile(path) and f.endswith('.html'):
	                        myList.append(path)
	                elif os.path.isdir(path):
                                ...
</code>

While this seems to work, it also seems wrong to have to guess how many
levels deep my directory structure is and copy, paste and indent the code
accordingly.  Is there a recursive find utility in Python similar to bash
find ?  For example:

find . -name '*.html'

will return all html files from current working directory and on, along
with their paths respective to the current working directory.  I looked at
string module find in the Python documentation and shutils and did not
find the analog.