寫腳本實現:把電腦里面某個目錄 所有超過5兆的文件 列出來;
方法一:首先想到的是用遞歸方法,依次判斷os.listdir列出當前目錄下文件或者文件夾,如果是文件,判斷大小處理,是文件夾,遞歸查找。
#coding=utf-8 import os count=0 #參數path為絕對路徑,size為文件限制單位M def findSizeFile(path,size): #全局變量,統計文件個數 global count if os.path.isfile(path): if os.path.getsize(path)>size*1024*1024: print u"文件:",os.path.basename(path).decode('gb2312'), u"大小:",os.path.getsize(path) , u"路徑在:",os.path.dirname(path).decode('gb2312') count+=1 else: pass else: for p1 in os.listdir(path): findSizeFile(os.path.join(path,p1),size)
方法二:使用os.walk遍歷目錄,返回三元組(dirpath,dirnames,finenames),dirpath表示當前的路徑,是一個字符串;dirnames是一個列表,表示當前路徑下的子目錄;filenames是一個列表,表示當前路徑下包含的文件;
#coding=utf-8 import os count=0 #參數path為絕對路徑,size為文件限制單位M def findSizeFile2(path,size): global count tuples=os.walk(path) for root,dirs,files in tuples: for file in files: if os.path.getsize(os.path.join(root,file))>size*1024*1024: count+=1 print u"文件:",os.path.join(root,file),u"大小:",os.path.getsize(os.path.join(root,file))
