简体   繁体   中英

Python - how to match directories using fnmatch

I'm trying to use fnmatch to match directories in Python. But instead of only returning the directories that match the pattern, it's returning either all directories or none.

For example: F:\\Downloads has subdirectories \\The Portland Show, \\The LA Show, etc

I'm trying to find files in the \\The Portland Show directory only, but it also returns The LAS show, etc.

Here's the code:

for root, subs, files in os.walk("."):
  for filename in fnmatch.filter(subs, "The Portland*"): 
    print root, subs, files

Instead of just getting the subdir "The Portland Show", I get everything in the directory. What am I doing wrong?

I would just use glob :

import glob
print "glob", glob.glob('./The Portland*/*')

There are some tricks you can play though if you really want to use os.walk for one reason or another... For example, lets assume that the top directory only contained more directories. Then you can make sure you only recurse into the correct ones by modifying the subs list in place:

for root,subs,files in os.walk('.'):
    subs[:] = fnmatch.filter(subs,'The Portland*')
    for filename in files:
        print filename

Now in this case, you will only recurse into directories which start with The Portland and then you will print all of the filenames in there.

.
+ The Portland Show
|   Foo
|   Bar
+   The Portland Actors
|     Benny
|     Bernard
+   Other Actors
|     George
+ The LA Show
|   Batman

In this case, you'll see Foo , Bar , Benny and Bernard but you won't see Batman .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM