如果在python中找不到文件,是否可以抛出异常?

时间:2019-06-07 15:21:40

标签: python csv email smtplib yagmail

我正在编写一个程序,以便可以轻松地将电子邮件发送给人员列表,并向每个收件人发送一个唯一的文件。该程序以.csv文件的形式读取列表,其中包含每个收件人的姓,名,电子邮件地址和各自的附件,使用模板自定义具有收件人姓名的每封电子邮件,并附加其文件。 / p>

代码可以在下面看到。我在主题行和电子邮件地址中使用了占位符,并隐藏了电子邮件的实际文本,但是您应该可以理解。 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”之类的文本的电子邮件,而不是实际的附件。如果找不到该文件,是否有一种引发异常的方法,因此电子邮件发送时不带任何真实附件?

3 个答案:

答案 0 :(得分:0)

您可以编写自己的异常:

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))

打印:

“找不到文件myfile.txt正在终止!!!”

答案 1 :(得分:0)

或者,如果您不希望发生异常,则可以跳过该行:

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上方添加一条打印语句。

答案 2 :(得分:0)

使用

import os

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

查看文件是否存在。