Recursive wildcard file search
Tim Golden
mail at timgolden.me.uk
Fri Jul 4 09:25:57 EDT 2008
[sorry; this got stuck in my outbox]
Robert Dailey wrote:
> Is there a way to perform a recursive file search using wildcards in
> python 3.0b1?
>
> For example, if I have:
>
> C:\foo\abc*xyz.*
>
> I want all files in C:\foo and all subfolders (recursively) of C:\foo
> that match the wildcard abc*xyz.* to be matched. In the end, I want a
> list of files that matched the search, as well as the directory they're
> located in.
I haven't checked but I doubt this has changed from Python 2.x.
Just use os.walk and filter on what you want. Vaguest and most
untested code sample:
<code>
import os
import fnmatch
ROOT = "c:/temp"
PATTERN = "*c*.zip"
filepaths = []
for dirpath, dirnames, filenames in os.walk (ROOT):
filepaths.extend (
os.path.join (dirpath, f) for f in fnmatch.filter (filenames, PATTERN)
)
</code>
If you need to match on directory names as well,
then you'd have to adjust accordingly.
TJG
More information about the Python-list
mailing list