import os import shutil directory = 'D:\\test\\' def move_folder_to_parent(folder_name): # 获取当前文件夹的绝对路径 current_path = os.path.abspath(folder_name) # 获取上上一级目录的路径 destination_path = os.path.abspath(os.path.join(current_path, "../..")) # 第二次检查目标文件夹是否存在,避免覆盖 target_path = os.path.join(destination_path, os.path.basename(current_path)) if not os.path.exists(target_path): # 移动文件夹 shutil.move(current_path, target_path) print(f"文件夹已成功移动到:{target_path}") else: print(f"目标路径 {target_path} 已存在,移动失败。") def del_empty_folder(folder_name): if os.path.isdir(folder_name): if os.path.isdir(file_path): if os.listdir(folder_name) != []: for filename in os.listdir(folder_name): child_file_path = os.path.join(folder_name, filename) del_empty_folder(child_file_path) else: shutil.rmtree(folder_name) # 列出目录下的所有文件和文件夹 for filename in os.listdir(directory): file_path = os.path.join(os.path.abspath(directory), filename) if os.path.isdir(file_path): for child_filename in os.listdir(file_path): childPath = os.path.join(os.path.abspath(file_path), child_filename) if os.path.isdir(childPath): for child_child_filename in os.listdir(childPath): childChildPath = os.path.join(os.path.abspath(childPath), child_child_filename) if os.path.isdir(childChildPath): move_folder_to_parent(childChildPath) if os.path.isfile(childChildPath): destination_path = os.path.abspath(os.path.join(childChildPath, "../..")) target_path = os.path.join(destination_path, child_child_filename) if not os.path.exists(target_path): shutil.move(childChildPath, destination_path) else: print(f"目标路径 {target_path} 已存在,移动失败。") del_empty_folder(directory)