天天看點

Python學習筆記(24)-Python檔案搜尋器Version1.0(可搜尋壓縮檔案中包含的檔案)1. 簡介2. 效果示範3. 源代碼

1. 簡介

本篇實作了一個檔案搜尋器,雖然是指令行界面的,但是可以快速搜尋指定目錄下的指定檔案,同時可以搜尋到壓縮檔案中包含的檔案。

2. 效果示範

以下是指令行下檢索F:盤下檔案夾名中包含Java的所有檔案資訊。

請輸入要搜尋的檔案所在的目錄
F:
請輸入搜尋檔案名包含字元串
Java
開始檢索[F:]目錄下包含[Java]的檔案
##查找過程中的異常:File is not a zip file
##查找過程中的異常:File is not a zip file
[查找結果]F:360data\重要資料\桌面\Eclipse for Java SE.lnk
[查找結果]F:360data\重要資料\桌面\工具箱\Eclipse for Java SE.lnk
[查找結果]F:遊戲\Java.zip
[查找結果]F:遊戲\Java.zip解壓後的:Java.doc
>>> 
      

3. 源代碼

#檔案搜尋工具(可搜尋zip内部檔案)
#-----------------------------------------------------子產品導入與變量定義
#導入子產品
import os,zipfile
#搜尋結果
result=[]
#-----------------------------------------------------函數定義部分
#目錄周遊函數
def SearchPath(path,keyword):
    for folder,subFolders,files in os.walk(path):
        for file in files:#檔案分析
            AnalyzeFile(folder,file,keyword)
        for subFolder in subFolders:#遞歸周遊
            SearchPath(subFolder,keyword)     
#檔案分析,是否包含指定字元串,是否壓縮檔案中包含keyword
def AnalyzeFile(folder,file,keyword):
    if keyword in file: #檔案名中包含關鍵字
        result.append(folder+"\\"+file)
    if file.endswith(".zip"):#壓縮檔案
        try:#對壓縮檔案分析中抛出的異常進行捕獲
            viewZip=zipfile.ZipFile(folder+"\\"+file)
            for name in viewZip.namelist():
                if keyword in name:
                    result.append(folder+"\\"+file+"解壓後的:"+name)
            viewZip.close()
        except Exception as ex:
            print("##查找過程中的異常:"+str(ex))
       
        

#-----------------------------------------------------程式流程部分
#擷取目錄資訊
print("請輸入要搜尋的檔案所在的目錄")
dir=input()
while os.path.exists(dir)==False:
    print("目錄不存在,請重新輸入")
    dir=input()

#擷取檔案資訊
print("請輸入搜尋檔案名包含字元串")
keyword=input()
while len(keyword)<=0:
    print("請輸入至少1個字元")
    keyword=input()
#開始檢索
print("開始檢索["+dir+"]目錄下包含["+keyword+"]的檔案")
#周遊
SearchPath(dir,keyword)
#輸出
for re in result:
    print("[查找結果]"+re)