Python Traversal directory tree (files that match output specific suffixes)

Source: Internet
Author: User

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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.