python实现移动二级目录下的文件到一级目录

python实现移动二级目录下的文件到一级目录

import os
import shutil
import sys


def move_to_work_folder(work_path, cur_path):
    """
    将work_folder下的所有子目录中的文件移到根目录中:
    :param work_path: 当前工作目录
    :param cur_path: 文件所在目录
    :return:
    """
    for filename in os.listdir(cur_path):
        if os.path.isfile(os.path.join(cur_path, filename)):
            shutil.move(os.path.join(cur_path, filename), os.path.join(work_path, filename))
        elif os.path.isdir(os.path.join(cur_path, filename)):
            move_work_folder(work_path, os.path.join(cur_path, filename))
        else:
            sys.exit("Should never reach here.")
    # remove empty folders
    if cur_path != work_path:
        os.rmdir(cur_path)


def move_to_up_folder(subpath, work_path, same_dirs):
    """
    将工作目录中的二级子目录下的文件或目录移到当前工作目录,并删除旧的二级子目录内容。
    :param subpath:二级目录
    :param work_path:当前工作目录
    :param same_dirs:工作目录下相同目录名称
    :return:
    """
    # 确认工作目录下是否存在相同目录
    same_dir_path = os.path.join(work_path, same_dirs)
    if os.path.exists(same_dir_path):
        print("工作目录中存在相同目录: {}".format(same_dir_path))
        # 若存在相同目录,拷贝当前二级目录的子目录到工作目录下同名目录中
        for thirdir in os.listdir(subpath):
            shutil.move(os.path.join(subpath, thirdir), same_dir_path)
        os.rmdir(subpath)
    else:
        shutil.move(subpath, work_path)


if __name__ == '__main__':
    root_path = os.getcwd()
    for subdirname in os.listdir(root_path):
        # 遍历当前文件夹下的二级目录名
        if os.path.isdir(os.path.join(root_path, subdirname)):
            # 得到当前文件夹下的二级目录完整路径
            subdirpath = os.path.join(root_path, subdirname)
            # 遍历二级目录下的文件
            for name in os.listdir(subdirpath):
                # 导入二级目录下的文件、当前工作目录的完整路径到move_to_up_folder函数中
                move_to_up_folder(os.path.join(subdirpath, name), root_path, name)
            os.rmdir(subdirname)

posted @ 2022-12-07 16:25  f_carey  阅读(422)  评论(0编辑  收藏  举报