[英]Python, Deleting oldest 2000 files if a Windows10 folder contains more than 10000 files
我知道在 NTFS 中,單個文件夾中可能有 4,294,967,295 個文件,而且這些文件很多,但是我會以某種方式控制文件夾中的文件數量(在我的情況下為 d:/screen/work/)每分鍾 60 張圖像。 我怎么能用 Python 做到這一點? 我能夠找到一個解決方案(下面)只刪除舊文件(在下面的代碼中超過 7 天)但不知道如何刪除最新的“n”個最舊的文件(例如 2000)如果文件夾包含多個“y”文件(例如 10000)。
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
通過創建一個新的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 進行排序可能既耗時又低效,但更好的方法會復雜得多
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.