亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我如何改進這個功能來刪除舊的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 關注
  • 155 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號