QQ 聊天记录太大了,自带的文件清理根本动不了那个 Image 文件夹。于是写了一个 Python 脚本,遍历 Group2 文件夹并选择删除 200 天前的图片。
import os
import datetime
from tqdm import tqdm
import math
dirToBeEmptied = os.path.join("D:\\Program Files\\QQ\\HistoryData\\13XXXXXXXX\\Image", "Group2")
delta = datetime.timedelta(days=200) # 删除 200 天以前的
now = datetime.datetime.now()
all_files = []
for root, dirs, files in tqdm(os.walk(dirToBeEmptied), desc="Walking through directories..."):
all_files.append((root, dirs, files))
count = 0
total_size_cleared = 0
with tqdm(all_files, desc="Searching and deleting old files...") as pbar:
for root, dirs, files in pbar:
for name in files:
file = os.path.join(root, name)
ctime = datetime.datetime.fromtimestamp(os.path.getmtime(file))
if ctime < (now - delta): # 若创建于 delta 天前
file_size = os.path.getsize(file)
os.remove(file) # 删除
count += 1
total_size_cleared += file_size
# 遍历,若文件夹为空,则删除
for root, dirs, files in os.walk(dirToBeEmptied, topdown=False):
if not dirs and not files:
os.rmdir(root)
# Convert size to human-readable format
def convert_size(size_bytes):
if size_bytes == 0:
return "0B"
size_name = ("B", "KB", "MB", "GB", "TB")
i = int(math.floor(math.log(size_bytes, 1024)))
p = math.pow(1024, i)
s = round(size_bytes / p, 2)
return f"{s} {size_name[i]}"
print(f"Total files deleted: {count}")
print(f"Total space cleared: {convert_size(total_size_cleared)}")