我正在研究一個專案,以從路徑中列出所有檔案和目錄及其遞回元素,函式代碼:
def recursive_search(path: str) -> "list[str]":
"""get all files from an absolute path
:param path: absolute path of the directory to search
:type path: str
:return: a list of all files
:rtype: list[str]
"""
found_files = []
if not os.path.isdir(path):
raise RuntimeError(f"'{path}' is not a directory")
for item in os.listdir(path):
full_path = os.path.join(path, item)
if os.path.isfile(full_path):
found_files.append(full_path)
elif os.path.isdir(full_path):
found_files.extend(recursive_search(full_path))
return found_files
我這樣呼叫函式:
if __name__ == '__main__':
user = getuser()
directory = "C:\\Users\\" user "\\Desktop\\archivos"
path = (recursive_search(directory))
它可能會忽略一個檔案,例如我想從“C:\Users\XXX\Desktop”獲取所有目錄和檔案,但我不想捕獲檔案“C:\Users\XXX\Desktop\desktop”。 ini”,我該怎么做?
謝謝。
uj5u.com熱心網友回復:
我相信你的例子應該是直截了當的。您可以進一步改進它以獲得相對路徑。
for item in os.listdir(path):
full_path = os.path.join(path, item)
if os.path.isfile(full_path):
if not os.path.samefile(full_path, 'C:\\Users\\XXX\\Desktop\\desktop.ini'):
found_files.append(full_path)
elif os.path.isdir(full_path):
found_files.extend(recursive_search(full_path))
return found_files
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/464512.html
標籤:Python 数组 python-3.x
