0

I'm very new to python.

I have a folder called "etc" with a filename password.txt when generates every night. I would like to run a python script in windows task on daily basis to check if password.txt doesn't exist then send email to abc@ouremail.co.uk else do not send any email. I want to trigger email based on the below condition. When the condition is "false" send email else no action taken. How can I achieve it, any help on this would be greatly appreciated.

os.path.isfile("/etc/password.txt") True

Kind regards,

Biswa

Biswa
  • 335
  • 1
  • 21
  • post the code you have tried – deadshot Apr 21 '20 at 08:39
  • 2
    you can use the [task schedualer](https://www.jcchouinard.com/python-automation-using-task-scheduler/) to scheduale your script to run daily. you can use smtplib to send eails, [here](https://www.freecodecamp.org/news/send-emails-using-code-4fcea9df63f/) is an example – Nullman Apr 21 '20 at 08:43

1 Answers1

1

Check if File Exists using the os.path Module

The os.path module provides some useful functions for working with pathnames. The module is available for both Python 2 and 3

import os.path

if os.path.isfile('filename.txt'):
    print ("File exist")
else:
    print ("File not exist")

Then to send an email you can use smtplib (one topic here)

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

msg = MIMEMultipart()
msg['From'] = 'me@gmail.com'
msg['To'] = 'you@gmail.com'
msg['Subject'] = 'simple email in python'
message = 'here is the email'
msg.attach(MIMEText(message))

mailserver = smtplib.SMTP('smtp.gmail.com',587)
# identify ourselves to smtp gmail client
mailserver.ehlo()
# secure our email with tls encryption
mailserver.starttls()
# re-identify ourselves as an encrypted connection
mailserver.ehlo()
mailserver.login('me@gmail.com', 'mypassword')

mailserver.sendmail('me@gmail.com','you@gmail.com',msg.as_string())

mailserver.quit()
Ronan
  • 36
  • 3
  • 1
    Thank you for your answer. Is there any way i can specify file format like *.txt instead of specifying the name of the file? – Biswa Apr 21 '20 at 09:28
  • 1
    Then [glob](https://docs.python.org/3/library/glob.html) is what you need `import glob if glob.glob('*.csv'): print ("File exist")` – Ronan Apr 21 '20 at 09:40