【发布时间】:2021-11-06 09:49:47
【问题描述】:
我正在使用 Python 开展一个项目,通过该项目我将电子邮件批量发送到 CSV 文件中的联系人列表。
我可以让电子邮件发送工作正常,但如果 CSV 文件中有一些缺失值,我希望能够添加一些错误处理。
我的 CSV 文件只包括:record_id、retailer、first_name、last_name 和 email。
我希望能够使用“if”语句捕获这些“错误”并将它们添加到一个空列表中。
然后,我将使用填充的列表来存储缺失值的信息,以便我可以使用该列表在代码的其他位置显示错误(仍然不确定要在哪里显示错误)。
我遇到的问题是我无法将“if”语句中的值添加到空列表中。它只打印空列表。
这是我的电子邮件发送部分的代码示例:
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
try:
server.login(sender_email, password)
except SMTPAuthenticationError:
print("Username and/or password you entered is incorrect")
try:
with open("contacts.csv") as file: # Sending Multiple Personalized Emails using a CSV file
reader = csv.reader(file)
next(reader) # Skip header row
missing = []
for record_id, retailer, first_name, last_name, email in reader:
if not retailer:
missing.append("Record ID " + record_id + " has Retailer name missing!")
continue
if not first_name:
missing.append("Record ID " + record_id + " has First name missing!")
continue
if not last_name:
missing.append("Record ID " + record_id + " has Last name missing!")
continue
if not email:
missing.append("Record ID " + record_id + " has Email missing!")
continue
print(missing)
server.sendmail(
sender_email,
email,
message.as_string().format(
record_id=record_id,
retailer=retailer,
first_name=first_name,
last_name=last_name,
email=email,
previous_month=previous_month,
year=year),
)
print("Emails sent!")
except Exception as e:
print("Emails not sent!")
print(e)
except SMTPException as e2:
print(e2)
这是示例 CSV 文件:
record_id,retailer,first_name,last_name,email
1,Store 1,Bob,Doe,example@example.com
2,Store 2,Jane,Lang,example@example.com
3,Store 3,Bill,Rowe,example@example.com
4,Store 4,Rachel,Greene,, (missing email error test)
5,Store 5,,Geller,example@example.com, (missing first name error test)
6,,Joey,Tribiani,example@example.com (missing retailer error test)
【问题讨论】:
-
我是否正确理解您的问题归结为“为什么
if not retailerfalse”(等等)?您是否检查过您在if语句中使用的变量的值? -
可能是所有“错误”都仅附加在末尾(所有不良示例都在 csv 末尾),在这种情况下,添加任何内容时都不会打印列表因为
continue -
请始终在您的minimal reproducible example 中包含部分数据。具体来说,您的代码遇到问题的文件中的几行。将它们复制并粘贴到问题中,然后格式化为代码。
-
为什么有两个
if not retailer:条件?由于第一个执行continue,第二个永远不会执行。 -
@Matiiss 感谢您的意见。你是对的,因为我在 csv 文件的末尾放置了故意的 3 个错误行。但是,当我使用仅带有“打印”而不是“附加”的普通 if 语句时,错误会打印到控制台,但 .append 似乎不起作用。注意:我删除了“继续”语句并更新了代码。
标签: python list if-statement error-handling