Python批量删除多文件夹文件遇FileNotFoundError问题求助
解决Python删除指定文件时的FileNotFoundError问题
问题描述
需要从多个文件夹中删除Indices.txt文件,要求文件存在则删除,不存在则跳过继续处理下一个文件夹。但当前运行代码时,遇到不存在的文件会抛出FileNotFoundError错误。
当前使用的代码:
import os N = [i+1 for i in range(101)] I=[] for i in N: if i in I: continue os.remove(rf"C:\Users\User\OneDrive - Technion\Research_Technion\Python_PNM\Surfactant A-D\220 nodes_seed75_var1_1000stepsize_0.4initial_K_1e3\{i}\Indices.txt")
报错信息:
FileNotFoundError: [WinError 2] The system cannot find the file specified.
解决方案
方法1:先检查文件存在性再删除
通过os.path.isfile()判断目标文件是否存在且为普通文件,确认后再执行删除操作,避免触发不存在错误。
修改后的代码:
import os # 提取基础路径,避免重复书写 base_dir = r"C:\Users\User\OneDrive - Technion\Research_Technion\Python_PNM\Surfactant A-D\220 nodes_seed75_var1_1000stepsize_0.4initial_K_1e3" N = [i+1 for i in range(101)] I = [] for i in N: if i in I: continue # 用os.path.join拼接路径,适配不同系统的路径格式 target_file = os.path.join(base_dir, str(i), "Indices.txt") # 确认文件存在且是普通文件 if os.path.isfile(target_file): os.remove(target_file)
方法2:用异常捕获处理(更推荐)
即使文件存在,也可能遇到权限不足、文件被占用等问题,用try-except可以针对性处理各类异常,保证程序不会中断。
修改后的代码:
import os base_dir = r"C:\Users\User\OneDrive - Technion\Research_Technion\Python_PNM\Surfactant A-D\220 nodes_seed75_var1_1000stepsize_0.4initial_K_1e3" N = [i+1 for i in range(101)] I = [] for i in N: if i in I: continue target_file = os.path.join(base_dir, str(i), "Indices.txt") try: os.remove(target_file) except FileNotFoundError: # 文件不存在,直接跳过 pass except PermissionError: print(f"无法删除 {target_file}:权限不足") except Exception as e: print(f"删除 {target_file} 时发生未知错误:{str(e)}")
内容的提问来源于stack exchange,提问作者KeplerNick123
相关产品推荐
相关产品推荐

