Python implements a method of scanning subdirectories and files under a specified directory _python

Source: Internet
Author: User

This article describes using Python to scan files in a specified directory, or a function that matches a specified suffix and prefix. The steps are as follows:

If you want to scan files in a specified directory, including subdirectories, you need to call Scan_files ("/export/home/test/")

If you want to scan a file (such as a jar package) for a specific suffix in a specified directory, including subdirectories, call Scan_files ("/export/home/test/", postfix= ". Jar")

If you want to scan files (such as test_xxx.py) for a specific prefix in a specified directory, including subdirectories, call Scan_files ("/export/home/test/", postfix= "Test_")

The specific implementation code is as follows:

#!/usr/bin/env python
#coding =utf-8
 
import OS
 
def scan_files (directory,prefix=none,postfix=none):
  files_list=[]
   
  for root, sub_dirs, files in Os.walk (directory): For
    special_file in Files:
      if postfix:
        if Special_file.endswith (postfix):
          files_list.append (Os.path.join (root,special_file))
      elif Prefix:
        if Special_file.startswith (prefix):
          files_list.append (Os.path.join (root,special_file))
      else:
        files_list.append (Os.path.join (root,special_file)) return
              
  files_list

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.