C盘快满了,想根据文件夹大小判断删掉一些东西,弹窗选择文件夹,获取子文件夹的属性,打印文件夹大小并按照由大至小排名。GPT写的,有问题喷GPT。
[Python] 纯文本查看 复制代码 import os
import tkinter as tk
from tkinter import filedialog
def get_folder_size(folder_path):
total_size = 0
for dirpath, dirnames, filenames in os.walk(folder_path):
for f in filenames:
fp = os.path.join(dirpath, f)
if os.path.isfile(fp):
total_size += os.path.getsize(fp)
return total_size
def main():
# 创建Tkinter窗口
root = tk.Tk()
root.withdraw() # 隐藏主窗口
# 弹出文件夹选择对话框
folder_path = filedialog.askdirectory(title="选择文件夹")
if folder_path:
print(f"文件夹: {folder_path}\n")
# 存储子文件夹名称和大小的列表
folder_sizes = []
total_size = 0 # 用于汇总所有子文件夹的总大小
# 遍历文件夹中的每个子文件夹
for subfolder in os.listdir(folder_path):
subfolder_path = os.path.join(folder_path, subfolder)
if os.path.isdir(subfolder_path):
size = get_folder_size(subfolder_path)
folder_sizes.append((subfolder, size))
total_size += size # 累加每个子文件夹的大小到总大小
# 按大小排序(从大到小)
folder_sizes.sort(key=lambda x: x[1], reverse=True)
# 打印排序后的结果
for subfolder, size in folder_sizes:
print(f"子文件夹: {subfolder} - 大小: {size / (1024 ** 2):.2f} MB")
# 打印汇总信息
print("\n汇总:")
print(f"总大小: {total_size / (1024 ** 2):.2f} MB")
else:
print("未选择文件夹")
if __name__ == "__main__":
main()
|