简体   繁体   English

Python-如何使用fnmatch匹配目录

[英]Python - how to match directories using fnmatch

I'm trying to use fnmatch to match directories in Python. 我正在尝试使用fnmatch来匹配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 例如:F:\\ Downloads具有子目录\\ The Portland Show,\\ The LA Show等

I'm trying to find files in the \\The Portland Show directory only, but it also returns The LAS show, etc. 我试图仅在\\ The Portland Show目录中查找文件,但它还会返回LAS show等。

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. 我得到的不仅仅是目录的子目录,而不仅仅是目录“ The Portland Show”。 What am I doing wrong? 我究竟做错了什么?

I would just use glob : 我只会使用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. 如果确实出于某种原因使用os.walk ,则可以使用一些技巧。例如,假设顶层目录仅包含更多目录。 Then you can make sure you only recurse into the correct ones by modifying the subs list in place: 然后你就可以确保你只能通过修改递归到正确的那些subs在地方名单:

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开头的目录,然后在其中打印所有文件名。

.
+ 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 . 在这种情况下,您会看到FooBarBennyBernard但是不会看到Batman

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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