newb question: file searching

thebjorn BjornSteinarFjeldPettersen at gmail.com
Tue Aug 8 19:18:08 EDT 2006


jaysherby at gmail.com wrote:
[...]
> that?  And also, I'm still not sure I know exactly how os.walk() works.
>  And, finally, the python docs all note that symbols like . and ..
> don't work with these commands.  How can I grab the directory that my
> script is residing in?

os.getcwd() will get you the directory your script is in (at least as
long as you're running the script from the current directory :-)

Here's my version of how to it (comments below):

def collect_ext(*extensions):
    """Return a list of files from current directory and downwards
       that have given extensions. Call it like collect_ext('.py',
'.pyw')
    """
    res = []
    for dirname, _, files in os.walk(os.getcwd()):
	for fname in files:
	    name, ext = os.path.splitext(fname)
	    if ext in extensions:
		res.append(os.path.join(dirname, fname))
    return res

Each time around the outer for-loop, os.walk() gives us all the
filenames (as a list into the files variable) in a sub-directory. We
need to run through this list (inner for-loop), and save all files with
one of the right extensions. (os.walk() also gives us a list of all
subdirectories, but since we don't need it, I map it to the _ (single
underscore) variable which is convention for "I'm not using this
part").

note1: notice the "*" in the def line, it makes the function accept a
variable number of arguments, so you can call it as collect_ext('.py')
but also as collect_ext('.py', '.pyw', '.pyo'). Inside the function,
what you've called it with is a list (or a tuple, I forget), which
means I can use the _in_ operator in the if test.

note2: I use os.path.join() to attach the directory name to the
filename before appending it to the result. It seems that might be
useful ;-)

hth,
-- bjorn




More information about the Python-list mailing list