1. 程式人生 > >【Python】獲取當前目錄和子目錄下所有檔案或指定檔案的方法

【Python】獲取當前目錄和子目錄下所有檔案或指定檔案的方法

###Date: 2018.5.23

================================================================

方法一:os.listdir()

getallfiles.py

import os
import sys

allfile = []
def get_all_file(rawdir):
      allfilelist=os.listdir(rawdir)
      for f in allfilelist:
            filepath=os.path.join(rawdir,f)
            if os.path.isdir(filepath):
                  get_all_file(filepath)
            allfile.append(filepath)
      return allfile

if __name__=='__main__':
      if(len(sys.argv) < 2):
            print("Usage: getallfiles.py rawdir")
            exit()
      rawdir = sys.argv[1]
      #current = os.getcwd()
      allfiles = get_all_file(rawdir)
      print allfiles
      

在命令列中輸入:python getallfiles.py E:\

就會列出E盤下面所有目錄(包括子目錄)下的所有檔案。

方法二:os.walk()

getallfiles_v2.py

import os
import sys

allfiles = []
def get_all_file(rawdir):
      for root,dirs,files in os.walk(rawdir):
            for f in files:
                  #if(re.search('mp4$'),f):
                  allfiles.append(os.path.join(root,f))
            for dirname in dirs:
                  get_all_file(os.path.join(root,dirname))
      return allfiles

if __name__=='__main__':
      if(len(sys.argv) < 2):
            print("Usage: getallfiles.py rawdir")
            exit()
      rawdir = sys.argv[1]
      #current = os.getcwd()
      allfiles = get_all_file(rawdir)
      print allfiles
      

在命令列中輸入:python getallfiles_v2.py E:\

就會列出E盤下面所有目錄(包括子目錄)下的所有檔案。

參考:

https://www.cnblogs.com/sudawei/archive/2013/09/29/3346055.html

https://blog.csdn.net/KGzhang/article/details/72964785