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

使用Python PIL保存图片至文件夹触发FileNotFoundError,求解决

解决图片保存时的FileNotFoundError问题

问题原因

报错核心是你指定的保存路径./new_folder/car2.png中,new_folder文件夹不存在。PIL库的Image.save()方法不会自动创建不存在的目录,因此触发了找不到文件或目录的错误。

修复方案

在调用img.save()前,先检查并创建目标文件夹,用Python内置的os模块即可完成:

修改后的代码

from PIL import Image
from PIL import ImageDraw
import os

# 创建空白图片
FRAME_SIZE = (720,1280)
img = Image.new('RGB', FRAME_SIZE, color = 'black')

# 初始化绘图对象
I1 = ImageDraw.Draw(img)

# 添加文本
I1.text((100, 100), "nice Car", fill=(255, 32, 0))

# 展示图片
img.show()

# 创建目标文件夹(不存在则创建)
save_dir = "./new_folder"
if not os.path.exists(save_dir):
    os.makedirs(save_dir)

# 保存图片
img.save(os.path.join(save_dir, "car2.png"))

关键说明

  • 导入os模块处理文件系统操作
  • os.path.exists()检查目录是否存在
  • os.makedirs()递归创建目录(支持多级目录创建)
  • os.path.join()拼接路径,适配不同操作系统的路径分隔符

原代码与报错信息

原代码

from PIL import Image
from PIL import ImageDraw

# Open an Image
FRAME_SIZE = (720,1280)
img = Image.new('RGB', FRAME_SIZE, color = 'black')

# Call draw Method to add 2D graphics in an image
I1 = ImageDraw.Draw(img)

# Add Text to an image
I1.text((100, 100), "nice Car", fill=(255, 32, 0))

# Display edited image
img.show()

# Save the edited image
img.save("./new_folder/car2.png")

报错信息

Traceback (most recent call last):
  File "D:\\Python Projects\\devops-directive-hello-world\\trial.py", line 19, in <module>
    img.save("./new_folder/car2.png")
  File "C:\\Users\\Pushpendra\\Desktop\\Drone\\devops-directive-hello-world\\lib\\site-packages\\PIL\\Image.py", line 2317, in save
    fp = builtins.open(filename, "w+b")
FileNotFoundError: [Errno 2] No such file or directory: './new_folder/car2.png'

进程已结束,退出代码为1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 09:18:30