【问题标题】:Adding data to an empty list from 'if' statements从“if”语句将数据添加到空列表
【发布时间】: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 retailer false”(等等)?您是否检查过您在 if 语句中使用的变量的值?
  • 可能是所有“错误”都仅附加在末尾(所有不良示例都在 csv 末尾),在这种情况下,添加任何内容时都不会打印列表因为continue
  • 请始终在您的minimal reproducible example 中包含部分数据。具体来说,您的代码遇到问题的文件中的几行。将它们复制并粘贴到问题中,然后格式化为代码。
  • 为什么有两个if not retailer:条件?由于第一个执行continue,第二个永远不会执行。
  • @Matiiss 感谢您的意见。你是对的,因为我在 csv 文件的末尾放置了故意的 3 个错误行。但是,当我使用仅带有“打印”而不是“附加”的普通 if 语句时,错误会打印到控制台,但 .append 似乎不起作用。注意:我删除了“继续”语句并更新了代码。

标签: python list if-statement error-handling


【解决方案1】:

continue 语句跳过循环体的所有其余部分并进入下一次迭代。如果第一个 if not retailer: 条件成功,您将不会执行任何其他测试。

与其在每个if 块中执行continue,不如设置一个变量来指示该记录是否有效。这使您可以检查所有字段。然后在所有检查之后,测试这个变量,看看你是否应该发送电子邮件。

print(missing) 应该退出循环。只有在所有验证都成功时才打印它。最后执行此操作以获取所有错误。

不相关的问题:try 中的 except: 块按顺序进行测试,因此您应该首先拥有更具体的异常类型。 except Exception: 应该是最后一个区块。

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:
                valid = True
                if not retailer:
                    missing.append("Testing")
                    valid = False
                if not retailer:
                    missing.append("Record ID " + record_id + " has Retailer name missing!")
                if not first_name:
                    missing.append("Record ID " + record_id + " has First name missing!")
                    valid = False
                if not last_name:
                    missing.append("Record ID " + record_id + " has Last name missing!")
                    valid = False
                if not email:
                    missing.append("Record ID " + record_id + " has Email missing!")
                    valid = False
                if valid:
                    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(missing)
        print("Emails sent!")
    except SMTPException as e2:
        print(e2)
    except Exception as e:
        print("Emails not sent!")
        print(e)

【讨论】:

  • 感谢您的意见@barmar!我已根据您的建议对代码进行了更改,但列表中仅添加了 1 个错误。我故意在 csv 文件中添加了 3 个“错误”行,因此应该捕获 3 个错误。
  • 请显示包含错误行的 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,, (缺少电子邮件错误测试) 5,商店 5,,Geller,example@example.com,(缺少名字错误测试) 6,,Joey,Tribiani,example@example.com(缺少零售商错误测试)
  • 没有格式化就没用了。粘贴到问题中的代码块中。
  • 道歉@barmar。这是我第一次发帖提问!我已经编辑了问题并添加了示例 csv 日期。希望这会有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多