写一个 Python 脚本,删除 QQ 老旧聊天图片

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)}")
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容