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

Python报FileNotFoundError[Errno2]:读取文件名却无法打开文件

问题原因与解决方法

核心问题是os.listdir()仅返回目标目录中的文件名,而非完整文件路径。当你调用Image.open(filename)时,Python会在当前脚本的工作目录(即脚本所在文件夹)中查找该文件,而非你指定的directory2目录,因此抛出文件不存在的错误。之前某个文件夹能运行,大概率是因为那个文件夹恰好是脚本的工作目录,文件名直接能匹配到。

解决方法

方法1:使用os.path.join拼接完整路径

修改代码,将目录路径与文件名拼接成完整路径:

import os
from PIL import Image
import numpy as np

directory2 = "folders_absolute_path"
for filename in os.listdir(directory2):
    # 拼接完整文件路径
    full_path = os.path.join(directory2, filename)
    # 仅处理.tif文件(可选,避免非目标文件报错)
    if filename.endswith('.tif'):
        imarray = np.array(Image.open(full_path))
        imarray[imarray == 1] = 19
        imarray[imarray == 2] = 20

方法2:使用pathlib模块(更简洁的现代写法)

pathlib是Python3.4+内置的面向对象路径处理模块,代码更易读:

from pathlib import Path
from PIL import Image
import numpy as np

directory2 = Path("folders_absolute_path")
# 直接遍历目录下的.tif文件
for file_path in directory2.glob("*.tif"):
    imarray = np.array(Image.open(file_path))
    imarray[imarray == 1] = 19
    imarray[imarray == 2] = 20

这样修改后,无论脚本工作目录是什么,都能正确定位到directory2中的文件,避免路径错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 02:25:38