You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python替换子目录中与指定文件夹同名的PDF文件

实现方案

核心逻辑

  1. 读取C:\PDF目录下所有PDF文件的文件名与完整路径
  2. 递归遍历C:\Folders及其子目录,匹配所有与源PDF同名的文件
  3. 用源PDF文件覆盖匹配到的目标文件

代码实现

import shutil
from pathlib import Path

def replace_matching_files(source_pdf_dir: str, target_root_dir: str):
    source_path = Path(source_pdf_dir)
    target_path = Path(target_root_dir)

    # 构建源PDF文件映射:文件名 -> 完整路径
    source_pdfs = {pdf.name: pdf for pdf in source_path.glob("*.pdf")}
    if not source_pdfs:
        print("未在C:\\PDF目录下找到任何PDF文件")
        return

    # 递归遍历目标目录下的所有文件
    for target_file in target_path.rglob("*"):
        if target_file.is_file() and target_file.name in source_pdfs:
            source_pdf = source_pdfs[target_file.name]
            try:
                # 覆盖目标文件,保留文件元数据(创建/修改时间等)
                shutil.copy2(source_pdf, target_file)
                print(f"已替换: {target_file}")
            except Exception as e:
                print(f"替换失败 {target_file}: {str(e)}")

if __name__ == "__main__":
    replace_matching_files("C:\\PDF", "C:\\Folders")

可选调整

  • 若仅需替换同名的PDF文件(而非所有同名文件),将target_path.rglob("*")改为target_path.rglob("*.pdf")
  • 若无需保留文件元数据,可将shutil.copy2替换为shutil.copy

内容的提问来源于stack exchange,提问作者Maxence MELIN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 04:48:12