
python高效移动文件夹及内容,完整保留目录结构
如何在Python中移动一个文件夹,包括其所有子文件夹和文件,同时精确复制其原始目录结构? shutil.move() 函数似乎无法满足这一需求,因为它无法保留子目录。
解决方案
以下代码利用 os.walk() 遍历源文件夹,并使用 shutil.copytree() 和 shutil.copy2() 将所有内容复制到目标位置,完美保留原有目录结构。 复制完成后,再删除源文件夹。
import shutil, os
source_dir = '/path/to/source_directory'
destination_dir = '/path/to/destination_directory'
# 创建目标目录,如果不存在
os.makedirs(destination_dir, exist_ok=True)
for root, dirs, files in os.walk(source_dir):
relative_path = os.path.relpath(root, source_dir)
destination_root = os.path.join(destination_dir, relative_path)
os.makedirs(destination_root, exist_ok=True) # 创建目标目录,如果不存在
for d in dirs:
shutil.copytree(os.path.join(root, d), os.path.join(destination_root, d))
for f in files:
shutil.copy2(os.path.join(root, f), os.path.join(destination_root, f))
# 删除源目录及其内容
shutil.rmtree(source_dir)
print("文件夹移动完成!")
此代码首先创建目标目录(如果不存在),然后遍历源目录,针对每个子目录和文件进行复制,最后删除源目录。 shutil.copy2() 保留元数据,os.makedirs(exist_ok=True) 避免因目标目录已存在而报错。 这提供了一个更健壮和完整的文件夹移动解决方案。
立即学习“Python免费学习笔记(深入)”;










