如何用os.walk实现目录及所有子目录的新/更新文件复制?
使用os.walk实现全目录文件同步
完全可以用os.walk实现递归遍历任意深度的子目录,替代你原有的两层遍历逻辑。下面是修改后的完整代码,保留了你原有的「跳过特定后缀文件」「仅复制新增/更新文件」的核心逻辑:
import os import shutil source_dir = r"C:\...." destination_dir = r"C:\....." # 遍历源目录下所有子目录及文件 for root, dirs, files in os.walk(source_dir): for file in files: # 跳过指定后缀的文件 if file.endswith('.849C9593-D756-4E56-8D6E-42412F2A707B'): continue # 构建源文件路径和目标文件路径 src_file = os.path.join(root, file) # 将源目录路径替换为目标目录路径,保证目录结构一致 rel_path = os.path.relpath(src_file, source_dir) dst_file = os.path.join(destination_dir, rel_path) # 确保目标文件所在的目录存在 dst_dir = os.path.dirname(dst_file) if not os.path.exists(dst_dir): os.makedirs(dst_dir) # 判断是否需要复制:文件不存在,或源文件更新时间比目标晚1秒以上 if not os.path.exists(dst_file) or os.stat(src_file).st_mtime - os.stat(dst_file).st_mtime > 1: shutil.copy2(src_file, dst_file)
关键逻辑说明
os.walk(source_dir):自动递归遍历源目录下的所有层级子目录,每次返回三个值:当前遍历的目录路径root、当前目录下的子目录列表dirs、当前目录下的文件列表files。- 路径映射:用
os.path.relpath获取文件相对于源目录的相对路径,再拼接目标目录得到对应的目标文件路径,保证复制后的目录结构和源目录完全一致。 - 目录创建:复制文件前先检查并创建目标文件所在的目录,避免因目录不存在导致复制失败。
- 复制判断:完全保留你原有的时间差判断逻辑,确保只复制新增或更新过的文件。
内容的提问来源于stack exchange,提问作者python_enthusiast90
相关产品推荐
相关产品推荐

