如何用Python替换子目录中与指定文件夹同名的PDF文件
实现方案
核心逻辑
- 读取
C:\PDF目录下所有PDF文件的文件名与完整路径 - 递归遍历
C:\Folders及其子目录,匹配所有与源PDF同名的文件 - 用源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
相关产品推荐
相关产品推荐

