天天看點

遞歸周遊檔案夾腳本

遞歸周遊某個檔案夾下的所有檔案是一項很常見的操作,總結通過shell和Python來遞歸周遊檔案夾的腳本如下。

  1.  shell version
    #!/bin/bash
     
    function walk()
    {
      for file in `ls $1`
      do
        local path=$1"/"$file
        if [ -d $path ]
         then
          echo "DIR $path"
          walk $path
        else
          echo "FILE $path"
        fi
      done
    }
     
    if [ $# -ne 1 ]
    then
      echo "USAGE: $0 TOP_DIR"
    else
      walk $1
    fi
               
  2. Python version 1, using os.listdir
    def os_list_dir(top_dir):
      for file in os.listdir(top_dir):
        file_path = os.path.abspath(os.path.join(top_dir, file))
        if os.path.isfile(file_path):
          print 'FILE', file_path
        elif os.path.isdir(file_path):
          print 'DIR', file_path
          os_list_dir(file_path)
               
  3. Python version 2, using os.walk
    def os_walk(top_dir):
      for parent, dirnames, filenames in os.walk(top_dir):
        for filename in filenames:
          print 'FILE', os.path.abspath(os.path.join(parent, filename))
        for dirname in dirnames:
          print 'DIR', os.path.abspath(os.path.join(parent, dirname))
        #del dirnames[:]  #uncomment this line to not walk recursively
               
  4. Python version 3, using os.path.walk
    def os_path_walk(top_dir):
      def print_name(arg, dirname, files):
        for file in files:
          file_path = os.path.abspath(os.path.join(dirname, file))
          if os.path.isfile(file_path):
            print 'FILE', file_path
          elif os.path.isdir(file_path):
            print 'DIR', file_path
        #del files[:] #uncomment this line to not walk recursively
     
      os.path.walk(top_dir, print_name, None)
               

本文出自 夜驚心的部落格,轉載請保留出處