Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

If/else condition is not working with Python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading