基于名称迁移Google Drive Takeout子目录至指定父目录
解决Google Drive Takeout目录迁移问题
原代码存在的问题
os.walk返回的subfolders是目录名称列表,直接和字符串'Drive'比较永远不成立shutil.copy参数顺序错误,正确格式是shutil.copy(源路径, 目标路径),且你误用了os.path(应该用os.path.join拼接路径)- 未处理
Photos目录的迁移需求 - 没有实现"不覆盖已迁移文件"的逻辑
修正后的代码方案
以下代码会遍历E:\gdrive\takeout下所有Takeout子目录中的Drive和Photos,将它们迁移到E:\storage下的同名目录,且不会覆盖已存在的文件:
import os import shutil from pathlib import Path # 定义源根目录和目标根目录 source_root = r"E:\gdrive\takeout" target_root = r"E:\storage" # 需要迁移的目标子目录名称 target_subdirs = ["Drive", "Photos"] # 遍历源目录下的所有文件和目录 for foldername, _, _ in os.walk(source_root): # 检查当前目录是否是Takeout下的目标子目录 current_path = Path(foldername) if current_path.parent.name == "Takeout" and current_path.name in target_subdirs: # 构造目标路径 dest_path = os.path.join(target_root, current_path.name) print(f"正在处理: {current_path} -> {dest_path}") # 递归复制目录,已存在的目录不会覆盖(Python 3.8+支持dirs_exist_ok) try: shutil.copytree(current_path, dest_path, dirs_exist_ok=True, copy_function=shutil.copy2) except shutil.SameFileError: print(f"跳过:{current_path} 与 {dest_path} 是同一路径") except Exception as e: print(f"处理 {current_path} 时出错: {str(e)}")
关键逻辑说明
- 使用
Path对象简化路径判断,精准识别Takeout下的Drive/Photos目录 shutil.copytree的dirs_exist_ok=True允许目标目录已存在,copy_function=shutil.copy2会保留文件元数据- 如果需要完全不覆盖任何已存在文件,可以把
copy_function替换为自定义函数:
def safe_copy(src, dst): if not os.path.exists(dst): shutil.copy2(src, dst) else: print(f"跳过已存在文件: {dst}") # 调用时替换copy_function参数 shutil.copytree(current_path, dest_path, dirs_exist_ok=True, copy_function=safe_copy)
内容的提问来源于stack exchange,提问作者mburn23
相关产品推荐
相关产品推荐

