我正在搜索大型目錄以將舊歸檔歸類爲特定順序。我嵌入了一個遞歸調用的函數,當它找到一個文件路徑匹配搜索條件的目錄時,它將它添加到'found'字典fdict
。使用os.scandir停留在遞歸目錄搜索中
預期的結果是,當在沒有子目錄的目錄上調用該函數時,該函數完成時不執行任何操作並移回到一個級別。
運行時,它被卡在第一個目錄中,它找不到子目錄,只是遞歸調用當前目錄進行搜索,陷入循環。
下面是代碼摘要,任何洞察爲什麼它是循環將不勝感激。
def scan(queries, directory):
fdict = {}
def search(queries, directory, fdict):
for entry in os.scandir(directory):
if entry.is_dir():
for x in queries:
if str(x) in entry.path:
fdict[str(x)] = entry.path
print("{} found and dicted".format(str(x)))
else:
search(queries, entry.path, fdict)
else: pass
search(queries, directory, fdict)
return fdict
請確保你沒有關注[符號鏈接](https://docs.python.org/3/library/os.html#os.DirEntry.is_symlink)嗎? –