【面試題】實現文件夾中文件的遍歷輸出
<p> </p>
<p>在之前的文章中://www.cnblogs.com/leiziv5/p/7411091.html,分享了基於python去遞歸查找文件中的文件。在後續的接觸中,可以基於深度遍歷和廣度遍歷來實現
</p>
<p>1.深度遍歷實現
對應實現思路:
1.創建棧
2.增加路徑
3.當棧不為空,處理棧的一個路徑
4.遍歷路徑下面的每一項
5.遇到文件夾加入到棧中
6.知道棧中元素為空,退出
import os path = '.' def GetAllDeep(path): stack = [] stack.append(path) # 處理棧,當棧為空時結束循環 while len(stack) != 0: # 從棧里取出數據 DirPath = stack.pop() # 目錄下所有文件 num = 0 file_num = 0 FileList = os.listdir(DirPath) # 循環處理每個文件 for FileName in FileList: FileAbsPath = os.path.join(DirPath,FileName) if os.path.isfile(FileAbsPath) == True: print("是文件",FileAbsPath) num += 1 else: # print("是目錄",FileAbsPath) stack.append(FileAbsPath) file_num += 1 print('當前文件數量:%s' % num, '當前文件夾數量%s' % file_num, '路徑是:%s' % (FileAbsPath))
我們看下最後的結果
2.廣度優先遍歷實現
思路
1.創建一個隊列 2.隊列增加文件路徑 3.當隊列不為空,獲取隊列 4.遍歷某個路徑,判斷是文件輸出,是文件夾加入隊列 5.直到隊列為空,程式終止運行。
看下最後的程式碼實現
import os, collections # 廣度遍歷目錄 def Get_All_Dir_Scope(path:str): #創建隊列 queue = collections.deque() # 進隊 queue.append(path) print("queue =", queue) while len(queue) != 0: # 出隊數據 File_Path = queue.popleft() # print(FilePath) # 找出所有的文件 num = 0 file_num = 0 FileNameList = os.listdir(File_Path) for fileName in FileNameList: fileAbsPath = os.path.join(File_Path, fileName) if os.path.isfile(fileAbsPath): print("是文件", fileAbsPath) num += 1 else: file_num += 1 queue.append(fileAbsPath) print('當前文件數量:%s' % num, '當前文件夾數量%s' % file_num, '路徑是:%s' % (fileAbsPath))
我們去傳遞一個路徑,遍歷裡面文件
path = '.' Get_All_Dir_Scope(path)
最後列印結果
可以看到上面的結果,和我們想要的輸出是一致的。
基於廣度遍歷的方式就實現完畢。其實很簡單。