如果在 python 中找不到文件,有没有办法抛出异常?

Is there a way to throw an exception if a file is not found in python?

我正在制作一个程序,以便可以轻松地将电子邮件发送给一组人,每个收件人都有一个唯一的文件。该程序以 .csv 文件的形式读取列表,其中包含每个收件人的姓氏、名字、电子邮件地址和各自的附件,使用模板自定义带有收件人姓名的每封电子邮件,并附上他们的文件。

代码如下。我为主题行和电子邮件地址使用了占位符,并隐藏了电子邮件的实际文本,但您应该能够理解。 email_data 变量是包含收件人信息的 .csv 文件最初加载到的位置。

import csv
import datetime
import sys

import smtplib
import yagmail

import tkinter as tk
from tkinter import filedialog
from tkinter import simpledialog

root = tk.Tk()
root.withdraw()

password = simpledialog.askstring("Password", "Enter password:", show='*')

current_date = datetime.datetime.now()

subject_line = f'xyz {current_date.strftime("%B")} {current_date.year} xyz File'

LNAMES = []
FNAMES = []
EMAILS = []
FILES = []

yag = yagmail.SMTP('xyz@xyx.com', password)

email_data = filedialog.askopenfilename(filetypes=[('.csv', '.csv')],
                                        title='Select the Email Data file')


def send_email():

    with open(email_data) as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        line_count = 0

        for row in csv_reader:
            last_name = row[0]
            first_name = row[1]
            email = row[2]
            file = row[3]

            LNAMES.append(last_name)
            FNAMES.append(first_name)
            EMAILS.append(email)
            FILES.append(file)

            line_count += 1

    try:
        for first_name, last_name, email, file in zip(FNAMES, LNAMES, EMAILS, FILES):
            txt = '...'
            yag.send(to=email,
                     subject=subject_line,
                     contents=[txt, file])

            print("Email(s) sent successfully")
            input("Press Enter to exit")
            sys.exit(1)

    except smtplib.SMTPAuthenticationError:
        print("Incorrect Email password entered")
        input("Press Enter to exit")
        sys.exit(1)


send_email()

我 运行 遇到的问题是,如果列出的文件不在工作目录中,则发送电子邮件时会在电子邮件底部附上一段文字,内容类似于 "file.xlsx" 而不是实际的附件。如果找不到文件,是否可以抛出异常,这样电子邮件就不会只是发送没有真正的附件?

您可以编写自己的异常:

class EmailAttachmentNotFoundException(Exception):
     pass

然后在附加文件的代码中:(为清楚起见删除了其余代码):

def send_email():

with open(email_data) as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0

    for row in csv_reader:
        last_name = row[0]
        first_name = row[1]
        email = row[2]
        file = row[3]
        if not os.isfile(file):
            raise EmailAttachmentNotFoundException('Could not find file {} Aborting!!!!'.format(file))

        LNAMES.append(last_name)
        FNAMES.append(first_name)
        EMAILS.append(email)
        FILES.append(file)

        line_count += 1

如果你想在线捕获它:

try:
    send_email()
except EmailAttachmentNotFoundException as e:
    # Modify the way the exception is raised and how it is captured, but this is the most basic way of getting what is inside 
    print(str(e))

这会打印:

'Could not find file myfile.txt Aborting!!!!'

或者,如果您不想例外,您可以跳过该行:

with open(email_data) as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0

    for row in csv_reader:
        last_name = row[0]
        first_name = row[1]
        email = row[2]
        file = row[3]
        if not os.isfile(file):
            continue             # <-----

        LNAMES.append(last_name)
        FNAMES.append(first_name)
        EMAILS.append(email)
        FILES.append(file)

        line_count += 1

continue 将跳过其余代码并返回到 for 循环。如果您想查看不存在的反馈,您可以在 continue 正上方添加打印语句。

使用

import os

if os.path.exists(file_path):
    do_someting()
else:
    raise SOME_ERROR()

查看文件是否存在。