为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

LEATH 2023-09-26 17:12:30
此脚本的目标是删除node_modules过去 15 天内未触及的所有内容。它目前正在工作,但是当它进入每个文件夹时,因为os.walk我失去了效率,因为我不必进入node_modules文件夹,因为它正是我想要删除的内容import osimport timeimport shutilPATH = "/Users/wagnermattei/www"now = time.time()old = now - 1296000for 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))
查看完整描述

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)


查看完整回答
反对 回复 2023-09-26
?
慕姐8265434

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 ]



查看完整回答
反对 回复 2023-09-26
  • 2 回答
  • 0 关注
  • 72 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信