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免费学习笔记(深入)”;
以上就是Python如何移动文件夹及其所有子文件夹和文件,同时保持原有目录结构?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号