【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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM