newb question: file searching

hiaips rosedb0 at gmail.com
Tue Aug 8 16:24:35 EDT 2006


> jaysherby at gmail.com wrote:
> > I'm new at Python and I need a little advice.  Part of the script I'm
> > trying to write needs to be aware of all the files of a certain
> > extension in the script's path and all sub-directories.  Can someone
> > set me on the right path to what modules and calls to use to do that?
> > You'd think that it would be a fairly simple proposition, but I can't
> > find examples anywhere.  Thanks.

dir_name = 'mydirectory'
extension = 'my extension'
import os
files = os.listdir(dir_name)
files_with_ext = [file for file in files if file.endswith(extension)]

That will only do the top level (not subdirectories), but you can use
the os.walk procedure (or some of the other procedures in the os and
os.path modules) to do that.

--Dave




More information about the Python-list mailing list