Ray's playground

 

Walking Directory Trees(Python Cookbook 2-16)

Precondition

1. os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])

Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).

Example

os.walk

        Output: C:\Download\27257633.flv
                     C:\Download\27294059.flv

2. fnmatch.fnmatch(filename, pattern)

Test whether the filename string matches the pattern string, returning true or false. If the operating system is case-insensitive, then both parameters will be normalized to all lower- or upper-case before the comparison is performed. If you require a case-sensitive comparison regardless of whether that’s standard for your operating system, use fnmatchcase() instead.

Example

fnmatch
Output:Y

 

Problem

You need to examine a "directory", or an entire directory tree rooted in a certain directory, and iterate on the files (and optionally folders) that match certain patterns.

Solution

Solution

 

Usage

Usage
Output: C:\Download\27257633.flv
             C:\Download\27294059.flv
             C:\Download\cd1.mp4

posted on 2009-02-20 21:57  Ray Z  阅读(363)  评论(0)    收藏  举报

导航