繁体   English   中英

如何改进此功能以删除旧的 node_modules 文件夹

[英]How can i improve this function to delete old node_modules folders

此脚本的目标是删除过去 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模块中的Pathrglob函数来仅查找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 中比 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 ]

但我认为你应该使用 npm 来管理旧包。 也许这篇文章可以帮助:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM