开发者

Find files (but ignore them in certain folders)

I want开发者_如何学Python to find files of a specific type in a certain directory. The directory has lots and lots of subfolders and I want to ignore certain ones. I am using the following code-

def locate(pattern, root=os.curdir):
    '''Locate all files matching supplied filename pattern in and below
    supplied root directory.'''
    for path, dirs, files in os.walk(os.path.abspath(root)):
        for filename in fnmatch.filter(files, pattern):
            yield os.path.join(path, filename)


for filename in locate("*.s2p"):
          #do something

I think there should be some way to change os.curdir to os.curdir (minus some folders) , or perhaps I can check current path and put in a conditional loop ? I tried os.cwd() but i got an error message saying 'module' object has no attribute 'cwd'


If you want to ignore some subdirectories while walking with os.walk, you can mutate the value of "dirs". E.g.

ignored = ["foo", "bar"]
for path, dirs, files in os.walk(os.path.abspath(root)):
    for dir in ignored:
        if dir in dirs: dirs.remove(dir)
    for filename in fnmatch.filter(files, pattern):
        yield os.path.join(path, filename)

This would skip all subdirectories named "foo" or "bar" while walking the directory tree.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜