如果在 csv 文件中找到字符串,如何通过 python 发送电子邮件警报?

How to send email alert through python if a string is found in a csv file?

我是 python 的新手,正在尝试了解如何发送电子邮件提醒。我有一个 csv 文件,下面是它的数据框:

,Latitude,Longtitude,LocationKey,MatchDescription
0,38.67694301003448,-77.7429029707531,609751,rooftop
1,29.372805012097956,-98.53188396363142,609750,rooftop
2,37.72961100923345,-122.38610096386918,609749,rooftop
3,42.509437395496974,-70.86884298867957,609748,rooftop
4,was not geocoded,rooftop
5,25.982770005233007,-80.16985001050395,609745,place

每天这个特定的 csv 都会重新生成新值,但是,偶尔,我会收到上述错误消息,说没有进行地理编码。 我想要一个脚本,每次该字符串出现在这个生成的 csv 中时,它都会向我发送一封电子邮件警报。

import pandas as pd
import smtplib
from email.message import EmailMessage

df = pd.read_csv('StgDimLocationEsri.csv')

cols_to_check = ["Latitude","Longtitude","LocationKey"]


def email_alert(subject,body,to):
            msg = EmailMessage()
            msg.set_content(body)
            msg['subject'] = subject
            msg['to'] = to
            # msg['from'] = from
            
            user = "xx@gmail.com"
            msg['from'] = user
            password = "clqdgqyfrleisynd"
            
            server = smtplib.SMTP("smtp.gmail.com", 587)
            server.starttls()
            server.login(user,password)
            server.send_message(msg)
            
            server.quit()
if __name__ == '__main__':
    email_alert("Hey","Error","yy.t@cfi.com")
    
for col in cols_to_check:
    if not pd.to_numeric(df[col], errors='coerce').all():
        email_alert()

问题是,即使这些列下只有数字,我也会收到一封电子邮件。我尝试用数字替换未进行地理编码的,但我仍然收到错误电子邮件

既然你有一个 csv 文件,最好使用 pandas 读取它,然后检查特定列中的所有值是否都是数字,同样地:

import pandas as pd
import smtplib
from email.message import EmailMessage

df = pd.read_csv('StgDimLocationEsri.csv')

cols_to_check = ["Latitude","Longtitude","LocationKey"]

#df = pd.DataFrame({'Latitude': [11.324342,343.4552,434.3, 'nan',-34895.6661,1,2], 'Longtitude': list('ABCDEFG'), 'LocationKey': [38.676943448,-38.6769438,34,23,12,56,67]})

def email_alert(subject,body,to):
    msg = EmailMessage()
    msg.set_content(body)
    msg['subject'] = subject
    msg['to'] = to
        
    user = "from_email@gmail.com"
    msg['from'] = user
    password = "pwd"
        
    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 a non-numeric value in column " + col + "."
     
        email_alert("Hey",body,"to_email@gmail.com")

Since I did not have access to the csv file I tried creating a sample DataFrame which has been commented out in the above code.