Search code examples
pythonlist-comprehension

How would you use list comprehension to output True with an If statement?


I have a debugger to get rid of bad files like this:

from os import path

for i in attachments: #Find bad attachments
    if not path.isfile(i):
        sys.exit("The attachment provided does not exist.")  #Raise exception

What is the best way to do this? Is this the most efficient way?

I tried doing this: [sys.exit(...) if not pathisfile(i) for i in attachments] but it just showed syntax error.


Solution

  • the most efficient way is to do a python assertion:

    from os import path
    
    for i in attachments:
      assert path.isfile(i),"the attachment you provided does not exist."