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

使用Python读取文本文件移动文件,如何在源文件缺失时保持脚本继续运行

Python文件移动脚本容错优化方案

你要实现跳过不存在的文件继续执行,有两种常用实现方式:

方案1:先判断文件存在再执行移动

在调用shutil.move前先校验源文件是否存在,不存在就直接跳过当前循环:

import shutil
import os

dst = r"C:/Users/Louis/Desktop/destination/"
src_root = r'C:/Users/Louis/Desktop/source/'

with open('test.txt', encoding='utf-8') as my_file: # 建议指定编码避免乱码
    for filename in my_file:
        file_name = filename.strip()
        # 跳过文本中的空行
        if not file_name:
            continue
        src_path = os.path.join(src_root, file_name)
        dst_path = os.path.join(dst, file_name)
        # 校验源文件是否存在
        if os.path.isfile(src_path):
            shutil.move(src_path, dst_path)
        # 不存在的文件直接跳过,可按需打开下方注释打印提示
        # else:
        #     print(f"文件{file_name}不存在,已跳过")
  • 用os.path.join拼接路径,避免手动写斜杠导致的拼写或跨平台兼容问题
  • 新增空行判断逻辑,避免文本里的空行导致无效处理

方案2:用异常捕获兼容更多异常场景

如果除了文件不存在,还希望遇到权限不足、文件被占用等报错时也能跳过处理,可直接用try-except包裹移动逻辑:

import shutil
import os

dst = r"C:/Users/Louis/Desktop/destination/"
src_root = r'C:/Users/Louis/Desktop/source/'

with open('test.txt', encoding='utf-8') as my_file:
    for filename in my_file:
        file_name = filename.strip()
        if not file_name:
            continue
        src_path = os.path.join(src_root, file_name)
        dst_path = os.path.join(dst, file_name)
        try:
            shutil.move(src_path, dst_path)
        except Exception as e:
            # 捕获所有执行异常,可按需打开下方注释打印错误信息
            # print(f"处理文件{file_name}失败:{str(e)},已跳过")
            continue

两种方案都可以实现需求,对稳定性要求高更推荐第二种方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 21:39:03