The module involved has the OS, fnmatch:1, through the method of the OS module to obtain dir, subdir, files, through the os.path.join can be stitched into the full path;
2, Fnmatch mainly through Fnmatch.fnmatch (name, patterns), in patterns to match the name element, to obtain a specific suffix of the file.
This feature code can be encapsulated for subsequent calls:
1 #!/usr/bin/env python2 ImportOS, Fnmatch3 4 defAll_files (Root, patterns='*', Single_level=false, yield_folders=False):5 #take a pattern out of a string and put it in the list6Patterns = Patterns.split (';')#multiple suffixes can be specified as the type of file to be obtained, through '; ' As separators7 forPath, subdir, filesinchOs.walk (Root):8 ifyield_folders:9 files.extend (subdir)Ten Files.sort () One forNameinchFiles: A forPatterninchPatterns: - ifFnmatch.fnmatch (name, patterns): - yieldos.path.join (path, name) the Break - ifSingle_level: - Break:
In order to verify the final result, (note that the final result is iterative), I have verified the specific example as follows:
1 for in All_files ('/usr/local/test', pattern='*.py' ):2 print path
。
Share with us!
Python Traversal directory tree (files that match output specific suffixes)