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

标签 python

此脚本的目标是删除过去 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 - 我如何改进这个功能来删除旧的node_modules文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64164950/

相关文章:

python - 如何在 Google Compute Engine 中通过 Python 访问 Google Cloud SQL

python - GCP dataproc with presto - 有没有办法使用 pyhive 通过 python 远程运行查询?

python - 与 SQLAlchemy 中列的切片和转换值的关系

python - Pandas 字符串提取所有匹配项

python - 我可以对 df.column 的元素进行分类并创建一个不带迭代输出的列(Python-Pandas-Np)吗?

python - Django:快速检索 manyToMany 字段的 ID

python - 返回 pandas 数据帧的函数

python - "for-in loop"的学习索引

python - 单个DataFrame列python/pandas中的groupby逗号分隔值

python - pandas 中多索引列的成对减法