Python 处理采集中的嵌套目录文件

需求

在管理文件时,我们常常需要从嵌套的目录结构中提取文件并清理空目录。

以下是一个 Python 脚本的演示,它可以自动整理指定目录中的所有文本文件,并将它们移动到主目录中,同时删除所有空的嵌套目录。

这个脚本特别适合于文件夹中包含多个子文件夹和文本文件的场景,可以帮助用户有效地整理文件结构。

脚本功能:

  1. 移动文本文件:将所有子目录中的 .txt 文件移动到主目录中。
  2. 删除空目录:在移动文件后,删除所有剩余的空目录。
  3. 统计信息:输出整理的文本文件总数和删除的空目录数量。

demo:

import os
import shutil

def move_txt_files(src_dir):
    total_txt_count = 0
    total_dirs_removed = 0

    # 遍历目录中的所有文件和子目录
    for root, dirs, files in os.walk(src_dir, topdown=False):
        for file in files:
            if file.endswith('.txt'):
                src_file = os.path.join(root, file)
                dest_file = os.path.join(src_dir, file)

                # 移动文件到目标目录
                shutil.move(src_file, dest_file)
                total_txt_count += 1

        # 删除空目录
        if root != src_dir:
            try:
                os.rmdir(root)
                total_dirs_removed += 1
            except OSError as e:
                print(f"Error removing directory {root}: {e}")

    return total_txt_count, total_dirs_removed

if __name__ == "__main__":
    source_directory = r'路径\到\目'
    
    # 执行文件移动和目录删除
    txt_count, dirs_removed = move_txt_files(source_directory)
    
    print(f"总共整理了 {txt_count} 个 txt 文件")
    print(f"删除了 {dirs_removed} 个嵌套文件夹")

评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注