The examples in this article describe how Python3 traverses a directory tree. Share to everyone for your reference. The implementation method is as follows:
Import OS, fnmatch# examines a directory tree that contains subdirectories, and iterates over all files according to a pattern # patterns such as: *.html, if case sensitive writable *. [Hh] [Tt] [Mm] [Ll] # Single_level True indicates that only the first layer # Yield_folders is checked to indicate whether subdirectories are displayed, false to only traverse files in subdirectories, # but does not return the letter name def all_files (Root, patterns= ' * ', Single_level=false, Yield_folders=false): # Take the pattern out of the string into the list patterns = Patterns.split (';') For path, subdirs, files in Os.walk (root): if yield_folders: files.extend (subdirs) files.sort () for Name in Files: for pattern in patterns: if Fnmatch.fnmatch (name, pattern): yield os.path.join (path, name) C10/>break if Single_level: Break for file in All_files (' d:\\pm ', ' *.s;*.c ', False, False):
It is hoped that this article is helpful to everyone's Python3 program design.