【开发】删除空文件夹的小工具

删除空文件夹小工具

目标:指定文件夹,遍历文件夹下所有文件夹,将空文件夹删除。

step1 测试案例和测试环境

创建测试环境:

import os

def create_directory_structure():
    # 创建测试文件夹结构
    os.makedirs("MainFolder/Folder1/SubFolder1/EmptySubFolder1")
    open("MainFolder/File1.txt", 'w').close()
    open("MainFolder/Folder1/File2.txt", 'w').close()
    open("MainFolder/Folder1/File3.txt", 'w').close()
    os.makedirs("MainFolder/Folder1/EmptyFolder1")
    os.makedirs("MainFolder/Folder2/EmptyFolder2")

def create_directory_structure():
    try:
        os.makedirs("MainFolder/Folder1/SubFolder1/EmptySubFolder1")
        print("目录创建成功: MainFolder/Folder1/SubFolder1/EmptySubFolder1")

        with open("MainFolder/File1.txt", 'w'):
            pass
        print("文件创建成功: MainFolder/File1.txt")

        # 添加创建 File2.txt 和 File3.txt 的代码
        with open("MainFolder/Folder1/File2.txt", 'w'):
            pass
        print("文件创建成功: MainFolder/Folder1/File2.txt")

        with open("MainFolder/Folder1/File3.txt", 'w'):
            pass
        print("文件创建成功: MainFolder/Folder1/File3.txt")

        os.makedirs("MainFolder/Folder1/EmptyFolder1")
        print("目录创建成功: MainFolder/Folder1/EmptyFolder1")

        os.makedirs("MainFolder/Folder2/EmptyFolder2")
        print("目录创建成功: MainFolder/Folder2/EmptyFolder2")

    except (PermissionError, FileExistsError) as e:
        print(f"发生错误: {e}")

if __name__ == "__main__":
    print("+++创建测试文件夹结构+++")
    create_directory_structure()

测试动作: 运行小工具,指定 MainFolder 作为输入参数。
结果预期: 所有空目录应该被成功删除,非空文件夹和文件应该保持不变。

测试环境的目标文件夹结构就是这样的:

MainFolder
│
├── File1.txt
│
└── Folder1
    ├── File2.txt
    ├── File3.txt
    ├── SubFolder1
    │   ├── EmptySubFolder1
    │   └── File4.txt
    └── EmptyFolder1
└── Folder2
    └── EmptyFolder2

下面的脚本是用来检查是否删除了空目录:

def check_directory_structure():
    # 检查不存在的目录
    try:
        path = "MainFolder/Folder1/SubFolder1/EmptySubFolder1"
        assert not os.path.exists(path), f"路径 '{path}' 应该不存在"
    except AssertionError as e:
        print(f"发生错误1: {e}")

    try:
        path = "MainFolder/Folder1/EmptyFolder1"
        assert not os.path.exists(path),f"路径 '{path}' 应该不存在"
    except AssertionError as e:
        print(f"发生错误2: {e}")
    try:
        path = "MainFolder/Folder2/EmptyFolder2"
        assert not os.path.exists(path),f"路径 '{path}' 应该不存在"
    except AssertionError as e:
        print(f"发生错误3: {e}")

    # 检查存在的目录和文件
    try:
        path = "MainFolder/Folder1"
        assert os.path.exists(path), f"路径 '{path}' 应该存在"
    except AssertionError as e:
        print(f"发生错误4: {e}")
        pass
    try:
        path = "MainFolder/Folder1/SubFolder1"
        assert os.path.exists(path), f"路径 '{path}' 应该存在"
    except AssertionError as e:
        print(f"发生错误5: {e}")
    try:
        path = "MainFolder/Folder2"
        assert os.path.exists(path), f"路径 '{path}' 应该存在"
    except AssertionError as e:
        print(f"发生错误6: {e}")
    try:
        path = "MainFolder/File1.txt"
        assert os.path.exists(path), f"路径 '{path}' 应该存在"
    except AssertionError as e:
        print(f"发生错误7: {e}")
    try:
        path = "MainFolder/Folder1/File2.txt"
        assert os.path.exists(path), f"路径 '{path}' 应该存在"
    except AssertionError as e:
        print(f"发生错误8: {e}")
    try:
        path = "MainFolder/Folder1/File3.txt"
        assert os.path.exists(path), f"路径 '{path}' 应该存在"
    except AssertionError as e:
        print(f"发生错误9: {e}")
 
 if __name__ == "__main__":
    print("+++创建测试文件夹结构+++")
    create_directory_structure()

    print("---执行删除动作---")

    print("===检查是否删除空目录===")
    check_directory_structure()

step2 写一个小工具,通过命令行删除空目录

import os
import argparse


def is_hidden(path):
    try:
        # 获取文件夹的状态信息
        attributes = os.stat(path).st_file_attributes

        # 检查隐藏属性
        return attributes & 2 != 0  # 如果是隐藏,则返回True
    except FileNotFoundError:
        return False


def delete_empty_directories(directory):
    for root, dirs, files in os.walk(directory, topdown=False):
        # 跳过隐藏文件夹
        dirs[:] = [d for d in dirs if not is_hidden(os.path.join(root, d))]

        for dir_name in dirs:
            current_path = os.path.join(root, dir_name)
            if not os.listdir(current_path):
                try:
                    print(current_path)
                    os.rmdir(current_path)
                    print(f"已删除空目录: {current_path}")
                except OSError as e:
                    print(f"无法删除目录 {current_path}: {e}")

def main():
    parser = argparse.ArgumentParser(description="删除空目录的小工具")
    parser.add_argument("directory", help="要进行空目录删除的目标文件夹路径")

    args = parser.parse_args()

    if os.path.exists(args.directory):
        delete_empty_directories(args.directory)
    else:
        print(f"目标文件夹 '{args.directory}' 不存在.")

if __name__ == "__main__":
    main()

os.walk函数中,topdown是一个布尔值参数,用于控制遍历目录的顺序。
如果topdown为True,os.walk将按照自顶向下的顺序遍历目录;如果为False,将按照自底向上的顺序遍历目录。默认情况下,topdown参数的值是True。

os.listdir 获取目录中的文件和子目录列表,然后检查列表是否为空。如果列表为空,说明目录是空的

在Windows系统中,文件或目录的隐藏属性通常由st_file_attributes属性的值来表示。隐藏属性的值是一个位掩码,其中隐藏属性的标志位是0x10。

os.stat(path).st_file_attributes: 表示文件或目录的属性,包括是否为隐藏属性。可以判断文件或目录是否被隐藏。

执行的结果是:
>> python testRun.py
+++创建测试文件夹结构+++
目录创建成功: MainFolder/Folder1/SubFolder1/EmptySubFolder1
文件创建成功: MainFolder/File1.txt
文件创建成功: MainFolder/Folder1/File2.txt
文件创建成功: MainFolder/Folder1/File3.txt
文件创建成功: MainFolder/Folder1/SubFolder1/File4.txt
目录创建成功: MainFolder/Folder1/EmptyFolder1
目录创建成功: MainFolder/Folder2/EmptyFolder2
---执行删除动作---
MainFolder\Folder1\SubFolder1\EmptySubFolder1
已删除空目录: MainFolder\Folder1\SubFolder1\EmptySubFolder1
MainFolder\Folder1\EmptyFolder1
已删除空目录: MainFolder\Folder1\EmptyFolder1
MainFolder\Folder2\EmptyFolder2
已删除空目录: MainFolder\Folder2\EmptyFolder2
MainFolder\Folder2
已删除空目录: MainFolder\Folder2
===检查是否删除空目录===

你可能感兴趣的:(笔记)