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

Python:文件夹不存在时如何跳过处理?求助解决方案

解决Python脚本文件夹不存在时的报错问题并实现需求功能

你遇到的核心问题是没有先校验目标路径的有效性就直接执行遍历操作,导致路径不存在时触发FileNotFoundError。我们可以通过先判断路径是否存在,再执行后续逻辑来解决这个问题,同时完成你需要的「检查文件是否存在」和「删除子文件夹」的功能。

修改后的完整代码

import os
import shutil

# 目标文件夹路径
target_path = r'/Users/scott/desktop/sales_data/store1/2018-05-10'

# 第一步:先确认目标路径是存在的文件夹
if os.path.exists(target_path) and os.path.isdir(target_path):
    # 检查文件夹中是否存在文件
    has_files = False
    for item in os.listdir(target_path):
        item_full_path = os.path.join(target_path, item)
        if os.path.isfile(item_full_path):
            has_files = True
            break
    
    if has_files:
        print("file available")
    else:
        print("no files found in this folder")
    
    # 删除文件夹内的所有子文件夹
    for entry in os.listdir(target_path):
        entry_path = os.path.join(target_path, entry)
        try:
            if os.path.isdir(entry_path):
                shutil.rmtree(entry_path)
                print(f"Successfully deleted subfolder: {entry_path}")
        except Exception as e:
            print(f"Failed to delete {entry_path}: {str(e)}")
else:
    # 路径不存在时直接跳过处理
    print(f"Folder {target_path} does not exist, skipping processing...")

关键修改点说明

  • 路径有效性校验:先用os.path.exists()和os.path.isdir()确认目标路径是真实存在的文件夹,从根源避免了不存在路径的遍历报错。
  • 文件存在检查逻辑:遍历路径下的所有条目,通过os.path.isfile()判断是否有文件存在,符合你要求的打印提示需求。
  • 异常处理保留:删除子文件夹时的异常捕获保留,能输出具体的删除失败原因,方便后续排查问题。
  • 跳过逻辑实现:当路径不存在时,直接打印提示并跳过所有后续处理步骤,完全匹配你的需求。

额外优化建议

如果需要批量处理多个文件夹,可以把上述逻辑封装成函数,再遍历文件夹列表调用,示例如下:

def process_single_folder(folder_path):
    if os.path.exists(folder_path) and os.path.isdir(folder_path):
        # 复制上面的检查文件、删除子文件夹逻辑即可
        has_files = False
        for item in os.listdir(folder_path):
            item_full_path = os.path.join(folder_path, item)
            if os.path.isfile(item_full_path):
                has_files = True
                break
        
        if has_files:
            print(f"file available in {folder_path}")
        else:
            print(f"no files found in {folder_path}")
        
        for entry in os.listdir(folder_path):
            entry_path = os.path.join(folder_path, entry)
            try:
                if os.path.isdir(entry_path):
                    shutil.rmtree(entry_path)
                    print(f"Deleted subfolder: {entry_path}")
            except Exception as e:
                print(f"Delete failed for {entry_path}: {str(e)}")
    else:
        print(f"Skip non-existent folder: {folder_path}")

# 批量处理示例
folder_list = [
    r'/Users/scott/desktop/sales_data/store1/2018-05-10',
    r'/Users/scott/desktop/sales_data/store1/2018-05-11',
    r'/Users/scott/desktop/sales_data/store1/2018-05-12'
]

for folder in folder_list:
    process_single_folder(folder)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:09:56