python写一个批量删除空文件夹程序

146 次阅读

本文最后更新于 2026年5月11日。

在工作中需要接触大量原始数据,这些数据中包含很多文件夹以及空文件夹。当去找数据时这些空文件夹会浪费很多时间,所以写一个程序删除所有空文件夹节约时间。
首先看一下程序界面:

使用很简单,打开可执行文件出现上述界面,点击OPEN选择需要清理的文件夹,再点击Run按钮就可以批量移除所选文件夹中的所有空文件夹了。

这里附上源代码:
“`

import os

import tkinter as tk

from tkinter import filedialog

def delete_empty_folders(dir_root):

for root, dirs, files in os.walk(dir_root):

# dirs 递归了所有文件夹,深度优先

# root 是每一次递归时的根目录

# files 是root下的文件

print(root)

del_list = []

if not os.listdir(root):

try:

os.rmdir(root)

del_list.append(root)

print(root, ‘is empty, delete’)

info_text.insert(‘end’, ‘[INFO] Deleted ‘ + root + ‘\n’)

info_text.see(‘end’)

except Exception as e:

info_text.insert(‘end’, ‘[ERROR] ‘ + str(e) + ‘\n’)

info_text.see(‘end’)

def run():

dir_root = workdir_entry.get()

delete_empty_folders(dir_root)

def open_folder():

workdir_entry.delete(0, ‘end’)

workdir_entry.insert(0, filedialog.askdirectory())

def UImain():

def quit_me():

print(‘quit’)

root.quit()

root.destroy()

log_dic = {}

global workdir_entry, info_text, ext_ori_text, ext_tar_text

root = tk.Tk()

root.title(‘Delete Empty Folders’)

root.geometry(‘770×700+30+30’)

root.protocol(“WM_DELETE_WINDOW”, quit_me)

workdir_label = tk.Label(root, text=’Work folder:’).grid(padx=’5′, pady=’5′,row=0, column=0, sticky=tk.W)

workdir_entry = tk.Entry(root, width=50)

workdir_entry.grid(padx=’5′, pady=’5′,row=0, column=1, sticky=tk.W)

workdir_open_btn = tk.Button(root, text=’Open’, command=open_folder).grid(padx=’5′, pady=’5′,row=0, column=2, sticky=tk.W)

info_label = tk.Label(root, text=’info text:’).grid(padx=’5′, pady=’5′,row=3, column=0, sticky=tk.W)

info_text = tk.Text(root, width=50, height=10)

info_text.grid(padx=’5′, pady=’5′,row=3, column=1, sticky=tk.W)

run_btn = tk.Button(root, width=7, height=1, text=’Run’, command=run).grid(padx=’5′, pady=’5′,row=5, column=2, sticky=tk.W)

quit_btn = tk.Button(root, width=7, height=1, text=’Quit’, command=quit_me).grid(padx=’5′, pady=’5′,row=5, column=15, sticky=tk.W)

root.mainloop()

if name == ‘main‘:

UImain()
   
“`

整个程序结构很简单,包括delete_empty_folders,run,open_folder,UImain四个函数。
UImain函数主要负责UI界面构建与函数调用。
delete_empty_folders函数是核心处理函数,实现递归查找空文件夹并删除的功能。
程序适合tkinter入门朋友学习实践,也可以用我打包好的程序直接作为工具软件使用。