Python,如果Windows10文件夹包含超过10000个文件,则删除最旧的2000个文件

2024-10-03 17:26:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道在NTFS中,单个文件夹中可能有4294967295个文件,这些文件很多,但是我会以某种方式控制文件夹中的文件数量(在我的情况下是d:/screen/work/),其中每分钟保存60个图像。 如何使用Python实现这一点?我能找到一个解决方案(如下)只删除旧文件(在下面的代码中超过7天) 但如果文件夹包含的文件超过“y”个(例如10000个),则不知道如何删除最新的“n”个最旧文件(例如2000个)

from pathlib import Path
import arrow
import os
import sys
    filesPath = r"d:/screen/work/"
    criticalTime = arrow.now().shift(hours=+5).shift(days=-7)
    for item in Path(filesPath).glob('*'):
        if item.is_file():
            itemTime = arrow.get(item.stat().st_mtime)
            if itemTime < criticalTime:
                os.remove(str(item.absolute()))
                print(str(item.absolute()))
                pass

Tags: 文件pathimport文件夹ifshiftositem
1条回答
网友
1楼 · 发布于 2024-10-03 17:26:52

一个简单的解决方法是创建一个新的dict,并将item.absolute()itemTime.timestamp添加为键值对

x[str(item.absolute())] = itemTime.timestamp

然后按值排序,

items_sorted = {k: v for k, v in sorted(x.items(), key=lambda item: item[1])}

并遍历第一个len(dict)-n

from pathlib import Path
from itertools import islice
import arrow
import os
import sys

x = {}
n = 10

filesPath = r"d:/screen/work/"
criticalTime = arrow.now().shift(hours=+5).shift(days=-7)
for item in Path(filesPath).glob('*'):
    if item.is_file():
        itemTime = arrow.get(item.stat().st_mtime)
        if itemTime < criticalTime:
            x[str(item.absolute())] = itemTime.timestamp


items_sorted = {k: v for k, v in sorted(x.items(), key=lambda item: item[1])}

for path, itemTime in islice(items_sorted.items(), len(x)-n):
    os.remove(str(item.absolute()))
    print(path)

此外,此解决方案无法在大量文件上很好地扩展。对整个dict进行排序可能既耗时又低效,但更好的方法会复杂得多

相关问题 更多 >