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

使用shutil.copy与多进程从列表复制文件时如何跳过不存在的文件?

解决方案

实现思路

将单次文件复制的逻辑封装为自定义函数,增加异常捕获逻辑,遇到文件不存在的错误时直接跳过,不抛出异常终止进程即可。

完整修改后代码

# Import libraries
import pandas as pd
import shutil
import os
import subprocess
from joblib import Parallel, delayed
import multiprocessing

# 自定义复制函数:存在则复制,不存在直接跳过
def copy_file_if_exist(f, dst):
    try:
        shutil.copy(f, dst)
        return True
    except FileNotFoundError:
        # 如果需要打印被跳过的文件可以取消下一行注释
        # print(f"文件{f}不存在,已跳过")
        return False

# define how many cores should be used
num_cores = 30 

os.chdir(source_folder)
# start to copy the tif images to the local drive
tmp = Parallel(n_jobs=num_cores)(delayed(copy_file_if_exist)(f, dst_folder) for f in source_files_list)

改动说明

  • 新增copy_file_if_exist函数:内部使用try-except捕获FileNotFoundError异常,遇到不存在的文件直接返回,不会抛出错误导致进程终止
  • 并行调用时替换为自定义的复制函数,原有并行逻辑不需要修改
  • 可选扩展:如果需要统计成功/失败的文件数量,或者记录跳过的文件明细,可以在函数对应分支增加日志打印或计数逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 18:36:04