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

Python运行抛出FileNotFoundError但目标目录存在对应文件如何解决

错误原因
  • os.listdir()返回的是目标目录下的纯文件名,不会携带目录路径。你运行代码时的工作目录和图片存储目录C:\\Users\\JoeBiden\\Desktop\\PJ\\AMP\\ImgLib不一致,直接调用open(randPic, 'rb')时,程序会在当前工作目录下查找对应文件,无法找到其他目录下的文件,所以抛出FileNotFoundError。
  • 你的代码还存在另外两处语法错误会导致后续运行报错:
    • 附件处理部分的msg-attach(file)为拼写错误,正确写法为msg.attach(file)
    • 附件实例化时的MimeApplication拼写错误,正确写法为MIMEApplication
修复方案
  1. 读取随机图片时,将存储目录路径和文件名拼接为完整路径再调用open
  2. 修正两处语法错误

修改后的完整代码如下:

import schedule, time, smtplib, random, os, sys, socket
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart

# Image randomization still under development

def message(subject="Python Notification",
            text="", img="", attachment=None):

    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg.attach(MIMEText(text))

    if type(img) is not list:
        img=[img]
    for one_img in img:
        path = "C:\\Users\\JoeBiden\\Desktop\\PJ\\AMP\\ImgLib"
        files=os.listdir(path)
        randPic=random.choice(files)
        # 拼接完整路径
        full_randpic_path = os.path.join(path, randPic)
        img_data = open(full_randpic_path, 'rb').read()
        msg.attach(MIMEImage(img_data,
                             name=randPic))

    if attachment is not None:
        if type(attachment) is not list:
            attachment = [attachment]
        for one_attachment in attachment:
            with open(one_attachment, 'rb') as f:
                # 修正MIMEApplication拼写
                file = MIMEApplication(
                    f.read(),
                    name=os.path.basename(one_attachment)
                )
            file['Content-Disposition'] = f'attachment;\
            filename="{os.path.basename(one_attachment)}"'
            # 修正attach方法调用拼写
            msg.attach(file)
    return msg

def mail():

    smtp=smtplib.SMTP('smtp.gmail.com', 587)
    smtp.ehlo()
    smtp.starttls()
    smtp.login('umomghaey@gmail.com', 'PEEENIS')
    msg = message("Pizza", "Pizza", r"C:\Users\JoeBiden\Desktop\PJ\AMP\ImgLib")
    to = ("cheeseburger@gmail.com")
    smtp.sendmail(from_addr="beesechurger@gmail.com",
                  to_addrs=to, msg=msg.as_string())
    smtp.quit()


schedule.every(2).seconds.do(mail)

while True:
    schedule.run_pending()
    time.sleep(1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 15:36:02