Below is the code – where I’m trying to fetch the file contains specific name if not I need an email to be sent. But in this case, else is always testing true and email has been sent though the file name is correct.
for file in test:
if (file.__contains__("Consolidated Engine run")) and (file.endswith('.xlsx')):
customer_file = os.path.join(newpath, file)
print(customer_file)
else:
import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = 'xyz.com'
mail.Subject = 'Change in the file name or format'
mail.Send()
quit()
Please guide me as where i’m wrong. I want my else condition not to execute if the file contains "Consolidated Engine run" and is .xlsx format
>Solution :
The problem in your code is from where you put the else block in the loop that loops through the files. Instead of checking every file in your setup, the email is sent for each one that doesn’t fit the condition in the if statement because the otherwise block runs for every file that doesn’t meet that criterion.
to fix the issues try the code below,
import os
import win32com.client as win32
# Assumes 'newpath' and 'test' are defined in your code
found = False
for file in test:
if "Consolidated Engine run" in file and file.endswith('.xlsx'):
customer_file = os.path.join(newpath, file)
print(customer_file)
found = True
break
if not found:
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = 'xyz.com'
mail.Subject = 'Change in the file name or format'
mail.Send()