Dr Chris Smith
Dr Chris Smith

Reputation: 25

How to loop through list of options inside if statement in python 2.7?

I am extracting items from a subdirectory containing a mixture of files that are audio files in different formats and with different suffixes e.g. _master or _128k.

I have specified higher up in the code a list of permitted extensions (e.g. .mp3) so that I extract only files of the right formats for processing.

I also have a list (suffixExcluded) containing filename suffixes (e.g. _syndication) I explicitly want to exclude from further processing.

How do I best write the line that effectively does:

if fileExtension in filesAllowed and [LIST OF EXCLUDED SUFFIXES] not in fileName:

Is there a neat, compact and elegant (pythonic) way of iterating through my list of exclusions within this if clause, or do I need to set up a subsidiary loop to test each item?

Upvotes: 2

Views: 58

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

You can filter as you go, passing a tuple of the extensions you want to keep and filtering those with any to remove any files with matching extensions that don't contain any substring from your list of excluded substrings.

exc = [LIST OF EXCLUDED SUFFIXES]

import os
for f in os.listdir("path"):
    if f.endswith((".mp4",".mp3",".avi")) and not any(e in f for e in exc):

You only need a single pass over the directory content without any need to build a list first.

If you want to replace the forbidden substrings and not just exclude you can use re.sub:

import os
import re
r = re.compile(r"|".join([e for e in exc]))
for f in os.listdir("path"):
    if f.endswith((".mp4",".mp3",".avi")):
        f = r.sub("",f)

Upvotes: 1

John Kugelman
John Kugelman

Reputation: 361585

You could use any with a generator expression to check all of the suffixes. You might also use a couple of temporary variables to aid readability.

included = fileExtension in filesAllowed
excluded = any(fileName.endswith(suffix) for suffix in suffixList)

if included and not excluded:
    ...

The expression inside any generates a series of bools, and any checks if any of them are True.

Upvotes: 0

Related Questions