没有这样的文件或目录:'download.jpg'

No such file or directory: 'download.jpg'

几个月前我做了一个电子邮件发件人,现在我有另一个项目,我想重新测试这个,但由于某种原因,它找不到基本上与 python 文件..

#Email Module Imports
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
#Imports Time Modules
import time
#Imports Numeric Module Functions
import random

def EmailSender():
    #Email Variables
    email_user = 'email'  # Sender Email (hidden for reason)
    email_password = 'password'  # Sender Password (hidden for reason)
    email_send = 'emailsend'  # Receiver Email (hidden for reason)
    PORT_EMAIL = 'smtp.gmail.com' 
    PORT = 587  # Email Port
    subject = 'email test'

    emailtest = "Test"
    msg = MIMEMultipart()
    msg['From'] = email_user
    msg['To'] = email_send  
    msg['Subject'] = subject  

    body = emailtest
    msg.attach(MIMEText(body, 'plain'))
    filename = 'download.jpg' 
    Email_attachment = open(filename, 'rb')

    part = MIMEBase('application', 'octet-stream')
    part.set_payload((Email_attachment).read()) 
    encoders.encode_base64(part)
    # adds email header with attachment
    part.add_header('Content-Disposition', "attachment; filename= "+filename)

    msg.attach(part)  # attaches email
    text = msg.as_string()
    srv = smtplib.SMTP(PORT_EMAIL, PORT)
    srv.starttls()  # runs the email SMTP
    srv.login(email_user, email_password) 
    srv.quit()  # stops

EmailSender()

项目的相对路径(文件夹)已更改。 为了万无一失,请使用从 EmailSend.py 所在位置派生的绝对路径将路径更改为 jpg

import os

currentDir= os.path.abspath(os.path.dirname(__file__))  # gets the current pytho file, SendEmail.py and returns absolute path (parent directory)
filepath=os.path.join(currentDir,"download.jpg")

作为@jozefow 回答的后续,

import pathlib

cwd = pathlib.Path.cwd()
filepath = cwd / "download.jpeg"

他们的回答和我的不同之处在于,我的不假设当前工作目录与文件目录相同。 任何一种假设都可能存在问题。

另一个关键区别是我的名义上更现代 python。