此脚本的目标是删除过去 15 天内未触及的所有 node_modules
。
它目前正在工作,但由于 os.walk
它进入每个文件夹,我失去了效率,因为我不必进入 node_modules
文件夹,因为这正是我要删除的内容
import os
import time
import shutil
PATH = "/Users/wagnermattei/www"
now = time.time()
old = now - 1296000
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:
print('Deleting: '+os.path.join(root, _dir))
shutil.rmtree(os.path.join(root, _dir))
最佳答案
如果您使用的是 Python 3,则可以使用 pathlib
模块中的 Path
和 rglob
函数来仅查找 node_modules
目录。这样,您将仅在 for
循环中迭代 node_modules
目录,并排除其他文件
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
目录(如果其父目录之一也是 node_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)
关于python - 我如何改进这个功能来删除旧的node_modules文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64164950/