如题,获取文件夹每个文件夹的大小
import os
import tkinter as tk
from tkinter import filedialog
from tkinter import ttk
def get_directory_size(path):
total_size = 0
for dirpath, dirnames, filenames in os.walk(path):
progress['maximum'] = len(filenames)
for f in filenames:
fp = os.path.join(dirpath, f)
# skip if it is symbolic link
if not os.path.islink(fp):
total_size += os.path.getsize(fp)
# Update the progress bar
progress['value'] += 1
progress.update_idletasks()
return total_size
def browse_directory():
path = filedialog.askdirectory()
if path:
sizes = {}
for dirname in next(os.walk(path))[1]:
dir_path = os.path.join(path, dirname)
if os.path.isdir(dir_path):
sizes[dirname] = get_directory_size(dir_path)
sorted_sizes = sorted(sizes.items(), key=lambda x: x[1], reverse=True)
for dirname, size in sorted_sizes:
size_mb = size / (1024 * 1024)
result_text.insert(tk.END, f"{dirname}: {size_mb:.2f} MB\n")
root = tk.Tk()
root.title("Directory Size Checker")
root.geometry("400x300")
root.resizable(True, True) # 第一个参数是宽度的布尔值,第二个参数是高度的布尔值
browse_button = tk.Button(root, text="Browse", command=browse_directory)
browse_button.pack()
progress = ttk.Progressbar(root, orient='horizontal', length=200, mode='determinate')
progress.pack()
result_frame = tk.Frame(root)
result_frame.pack(fill='both', expand=True)
result_text = tk.Text(result_frame)
result_text.pack(fill='both', expand=True)
scrollbar = tk.Scrollbar(result_text, command=result_text.yview)
scrollbar.pack(side='right', fill='y')
result_text.config(yscrollcommand=scrollbar.set)
root.mainloop()