在清理电脑视频图片文件时发现之前硬盘满了之后所遗留下来的0字节文件,自己又懒得一个个去找就直接用python写了个工具用来清理这些0字节文件
功能:
1、自定义目录路径清理该路径下所有子目录的全部0字节文件
2、检索时间比较长做了个进度条展示进度、百分比、剩余时间
下载链接:https://wwi.lanzoup.com/ihct70xk8e5g
代码块:
[Python] 纯文本查看 复制代码
from tkinter import messagebox
import os
from tkinter import filedialog, messagebox
import tkinter as tk
from tkinter import ttk
from datetime import timedelta
import time
def delete_zero_byte_files(directory):
count = 0
total_count = 0
for root, dirs, files in os.walk(directory):
total_count += len(files)
progress_bar['maximum'] = total_count
start_time = time.monotonic()
for root, dirs, files in os.walk(directory):
for file in files:
file_path = os.path.join(root, file)
if os.path.isfile(file_path) and os.path.getsize(file_path) == 0:
os.remove(file_path)
count += 1
progress_bar['value'] += 1
progress_percent.set(f'已完成{progress_bar["value"] / progress_bar["maximum"]:.2%}')
elapsed_time = time.monotonic() - start_time
estimated_time_left = (total_count - progress_bar['value']) / progress_bar['value'] * elapsed_time
estimated_time_left_str = str(timedelta(seconds=estimated_time_left))
progress_time_left.set(f'预计还需要{estimated_time_left_str}才能完成')
progress_window.update() # 更新窗口
end_time = time.monotonic()
elapsed_time_str = str(timedelta(seconds=end_time - start_time))
messagebox.showinfo('提示', f'已删除{count}个0字节文件!\n用时{elapsed_time_str}')
progress_window.destroy() # 关闭进度条窗口
def select_directory():
directory = filedialog.askdirectory(title='请选择待删除的目录路径')
if directory: # 用户选择了目录
global progress_window, progress_bar, progress_percent, progress_time_left
progress_window = tk.Toplevel(root)
progress_window.title('删除0字节文件')
progress_percent = tk.StringVar()
progress_percent.set('')
progress_time_left = tk.StringVar()
progress_time_left.set('')
progress_percent_text = tk.Label(progress_window, textvariable=progress_percent)
progress_percent_text.pack(padx=10, pady=5)
progress_time_left_text = tk.Label(progress_window, textvariable=progress_time_left)
progress_time_left_text.pack(padx=10, pady=5)
progress_bar = ttk.Progressbar(progress_window, orient='horizontal', mode='determinate')
progress_bar.pack(fill='x', padx=10, pady=10)
progress_window.geometry('400x150')
progress_window.resizable(False, False)
delete_zero_byte_files(directory)
if __name__ == '__main__':
root = tk.Tk()
root.geometry('300x100')
root.resizable(False, False)
select_directory_button = tk.Button(root, text='选择需要删除0字节文件的目录路径', command=select_directory)
select_directory_button.pack(padx=10, pady=10)
root.mainloop() # 进入主循环