【Python】查看指定目录(包括子目录)下指定年份的数量和占用量,附带windows可执行程序。

目录

安装依赖

代码 

打包为可执行程序


如果你使用了Anaconda,请先切换环境!!!

安装依赖

pip install tqdm aiofiles

代码 

新建一个find.py文件,将以下代码粘贴进去:

import os
import datetime
from concurrent.futures import ThreadPoolExecutor
from tqdm import tqdm


def process_file(file_paths, year):
    count = 0
    total_size = 0
    for file_path in file_paths:
        try:
            file_time = os.path.getmtime(file_path)
            if year == "":
                total_size += os.path.getsize(file_path)
                count += 1
                continue

            if datetime.datetime.fromtimestamp(file_time).year == year:
                total_size += os.path.getsize(file_path)
                count += 1
        except OSError as e:
            print(f"Error processing file {file_path}: {e}")
    return count, total_size


def find_files(target_dir, year, batch_size=500):
    total_count = 0
    total_size = 0

    with ThreadPoolExecutor() as executor:
        futures = []
        file_paths = []
        with tqdm(desc='正在收集文件', unit='个') as progress:
            for root, dirs, files in os.walk(target_dir, topdown=True):
                for file in files:
                    file_path = os.path.join(root, file)
                    file_paths.append(file_path)
                    progress.update(1)

                    if len(file_paths) >= batch_size:
                        futures.append(executor.submit(process_file, file_paths, year))
                        file_paths = []

        # 添加剩余的 file_paths
        futures.append(executor.submit(process_file, file_paths, year))
        for f in tqdm(futures, desc=f"处理任务(每{batch_size}个文件为一个任务)", unit="个"):
            count, size = f.result()
            total_count += count
            total_size += size

    return total_count, total_size


# 获取用户输入
target_directory = input("请输入目标目录: ")
year = input("请输入年份(直接回车表示全部): ")
s = "全部"
if year != "":
    s = f"{year}年"
    year = int(year)

file_count, total_size = find_files(target_directory, year, batch_size=1000)

print("------------------------统计结果------------------------")
print(f"{s}文件总数量: {file_count}")
print(f"{s}文件总占用: {(total_size / (1024 * 1024)):.2f} M | {(total_size / (1024 * 1024 * 1024)):.2f} G")
print("------------------------------------------------")
os.system('pause')

运行

python find.py

打包为可执行程序

安装pyinstaller

pip install pyinstaller

然后运行以下命令,在运行的目录中有一个dist文件夹,可执行程序就在其中。

pyinstaller --onefile find.py

可执行程序已提供,可自行下载:

find.exe - 蓝奏云


👍点赞,你的认可是我创作的动力 !
🌟收藏,你的青睐是我努力的方向!
✏️评论,你的意见是我进步的财富!     

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦境游子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值