我如何改进这个功能来删除旧的node_modules文件夹

此脚本的目标是删除node_modules过去 15 天内未触及的所有内容。


它目前正在工作,但是当它进入每个文件夹时,因为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))


LEATH
浏览 76回答 2
2回答

一只甜甜圈

如果您使用的是 Python 3,则可以使用Pathfrom pathlibmodule 和rglobfunction 来仅查找node_modules目录。这样,您将仅遍历循环node_modules中的目录for并排除其他文件import osimport timeimport shutilfrom pathlib import PathPATH = "/Users/wagnermattei/www"now = time.time()old = now - 1296000for path in Path(PATH).rglob('node_modules'):&nbsp; &nbsp; abs_path = str(path.absolute())&nbsp; &nbsp; if os.path.getmtime(abs_path) < old:&nbsp; &nbsp; &nbsp; &nbsp; print('Deleting: ' + abs_path)&nbsp; &nbsp; &nbsp; &nbsp; shutil.rmtree(abs_path)更新:如果您不想检查node_modules目录,其父目录之一是否也是 anode_modules并被删除。您可以使用os.listdir而不是非递归地列出当前目录中的所有目录,并将其与递归函数一起使用,以便您可以遍历目录树,并且始终先检查父目录,然后再检查其子目录。如果父目录是未使用的node_modules,则可以删除该目录并且不要进一步向下遍历到子目录import osimport timeimport shutilPATH = "/Users/wagnermattei/www"now = time.time()old = now - 1296000def traverse(path):&nbsp; &nbsp; dirs = os.listdir(path)&nbsp; &nbsp; for d in dirs:&nbsp; &nbsp; &nbsp; &nbsp; abs_path = os.path.join(path, d)&nbsp; &nbsp; &nbsp; &nbsp; if d == 'node_modules' and os.path.getmtime(abs_path) < old:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print('Deleting: ' + abs_path)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; shutil.rmtree(abs_path)&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; traverse(abs_path)traverse(PATH)

慕姐8265434

在 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 ]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python