Python FileNotFoundError 尽管显然已经找到文件

Python FileNotFoundError despite clearly having found the file

我正在开发一个 mailbomb 程序,它可以随机化给定目录中的图像。代码如下所示:

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)
        img_data = open(randPic, 'rb').read()
        msg.attach(MIMEImage(img_data,
                             name=os.path.basename(img_data)))

    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:
                file = MimeApplication(
                    f.read(),
                    name=os.path.basename(one_attachment)
                )
            file['Content-Disposition'] = f'attachment;\
            filename="{os.path.basename(one_attachment)}"'
            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)

当在 CMD 中 运行 时,出现以下错误:

        ret = self.job_func()
  File "C:\Users\JoeBiden\Desktop\PJ\AMP\MailRandomizer.py", line 46, in mail
    msg = message("Pizza", "Pizza", r"C:\Users\JoeBiden\Desktop\PJ\AMP\ImgLib")
  File "C:\Users\JoeBiden\Desktop\PJ\AMP\MailRandomizer.py", line 22, in message
    img_data = open(randPic, 'rb').read()
FileNotFoundError: [Errno 2] No such file or directory: 'RandImageFile.jpg'

对我来说,这个错误似乎是自相矛盾的,因为它清楚地告诉我它已经在正确的目录中找到了所需的文件之一。那就是 'RandImageFile.jpg'

os.listdir() 只给你文件名,所以尝试替换

files=os.listdir(path)

类似

files = [os.path.join(path, f) for f in os.listdir(path)]