import os import shutil

src_dir = 'D:/ABC/123' dst_dir = 'D:/123'

判断源目录是否存在

if not os.path.exists(src_dir): print('源目录不存在!') exit()

判断目标目录是否存在,如果不存在则创建

if not os.path.exists(dst_dir): os.mkdir(dst_dir)

遍历源目录下的所有文件和目录

for root, dirs, files in os.walk(src_dir): # 遍历目录下的所有子目录 for dir_name in dirs: # 拼接源目录和子目录路径 src_path = os.path.join(root, dir_name) # 拼接目标目录和子目录路径 dst_path = os.path.join(dst_dir, dir_name) # 如果目标目录已经存在,则删除目标目录 if os.path.exists(dst_path): shutil.rmtree(dst_path) # 移动子目录到目标目录 shutil.move(src_path, dst_path)

# 遍历目录下的所有子文件
for file_name in files:
    # 拼接源目录和子文件路径
    src_path = os.path.join(root, file_name)
    # 拼接目标目录和子文件路径
    dst_path = os.path.join(dst_dir, file_name)
    # 移动子文件到目标目录
    shutil.move(src_path, dst_path)

print('移动完成!')

Python 脚本:将非空目录内容移动到空目录

原文地址: https://www.cveoy.top/t/topic/mZnX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录