如果我的文件中缺少特定字符串,如何通过 python 发送电子邮件提醒?

How do I send an email alert through python if a particular string is missing in my file?

我是 python 和 smptplib 的新手 如果出现“#--- END -------------------------------- 我正在尝试发送电子邮件提醒" 在我的文件中未检测到。到目前为止,如果文件中有非数字,我可以发送电子邮件,但不确定如何创建一个函数,让你在字符串不存在或丢失时发送电子邮件

import pandas as pd
    import smtplib
    from email.message import EmailMessage
    
df = pd.read_fwf(r'factadwords.Rout', header=None)

    df
    Out[31]: 
                                                          0
    0     R version 4.0.4 (2021-02-15) -- "Lost Library ...
    1     Copyright (C) 2021 The R Foundation for Statis...
    2             Platform: x86_64-w64-mingw32/x64 (64-bit)
    3     R is free software and comes with ABSOLUTELY N...
    4     You are welcome to redistribute it under certa...
                                                    ...
    1337  > #--- END -----------------------------------...
    1338                                                  >
    1339                                      > proc.time()
    1340                               user  system elapsed
    1341                              73.89    7.00 1208.56
    
    [1342 rows x 1 columns]

def email_alert(subject,body,to):
    msg = EmailMessage()
    msg.set_content(body)
    msg['subject'] = subject
    msg['to'] = to
        
    user = "xx@gmail.com"
    msg['from'] = user
    password = "clqdgqyfrlccisynd"
        
    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.starttls()
    server.login(user,password)
    server.send_message(msg)
        
    server.quit()

if __name__ == '__main__':

    for col in cols_to_check:
        if not df[col].apply(lambda x: isinstance(x, (int, float))).all():
            body = "There is no END in the file" + col + "."
            print(body)
            email_alert("Hey",body,"xx.t@cinset.com")
            

我应该在我的代码中更改或添加什么?

您可以使用:

df[0].str.contains(end_str).any()

它将检查第 0 列中的任何行是否包含您的 END 字符串。如果其中至少一个包含所需的字符串,它将 return 为真。如果没有行包含该字符串,它将 return False.

你可以这样做:

import pandas as pd

end_str = '#--- END -----------------------------------'

df = pd.read_fwf(r'factadwords.Rout', header=None)

if not df[0].str.contains(end_str).any():
    print("There is no END in the file")
    email_alert("Hey",body,"xx.t@cinset.com")

pandas.Series.str.contains: https://pandas.pydata.org/docs/reference/api/pandas.Series.str.contains.html pandas.DataFrame.any: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.any.html