2 回答

TA貢獻1836條經驗 獲得超5個贊
如果您使用的是 Python 3,則可以使用Pathfrom pathlibmodule 和rglobfunction 來僅查找node_modules目錄。這樣,您將僅遍歷循環node_modules中的目錄for并排除其他文件
import os
import time
import shutil
from pathlib import Path
PATH = "/Users/wagnermattei/www"
now = time.time()
old = now - 1296000
for path in Path(PATH).rglob('node_modules'):
abs_path = str(path.absolute())
if os.path.getmtime(abs_path) < old:
print('Deleting: ' + abs_path)
shutil.rmtree(abs_path)
更新:如果您不想檢查node_modules目錄,其父目錄之一是否也是 anode_modules并被刪除。您可以使用os.listdir而不是非遞歸地列出當前目錄中的所有目錄,并將其與遞歸函數一起使用,以便您可以遍歷目錄樹,并且始終先檢查父目錄,然后再檢查其子目錄。如果父目錄是未使用的node_modules,則可以刪除該目錄并且不要進一步向下遍歷到子目錄
import os
import time
import shutil
PATH = "/Users/wagnermattei/www"
now = time.time()
old = now - 1296000
def traverse(path):
dirs = os.listdir(path)
for d in dirs:
abs_path = os.path.join(path, d)
if d == 'node_modules' and os.path.getmtime(abs_path) < old:
print('Deleting: ' + abs_path)
shutil.rmtree(abs_path)
else:
traverse(abs_path)
traverse(PATH)

TA貢獻1813條經驗 獲得超2個贊
在 Python 中,列表推導式比 for 循環更有效。但我不確定它是否更適合調試。
你應該嘗試這個:
[shutil.rmtree(os.path.join(root, _dir) \
for root, dirs, files in os.walk(PATH, topdown=False) \
? ? for _dir in dirs \
? ? ? ? if _dir == 'node_modules' and os.path.getmtime(os.path.join(root, _dir)) < old ]
添加回答
舉報