-1

I iterate across a list of files and want to check if they have one of many extensions before processing. Is it possible to accomplish this avoiding both these scenarios ? - Checking for each extension through an OR statement (i.e. hard-coding) - A loop within a loop

Construct so far:

#Iterate over files
for filename in os.listdir(os.getcwd()+dataDir):
    #iterate over ext (want to avoid)
    for u in ['jpg','txt'] :
        if filename.endswith(u):
            print("An ext of my choice found!")
        continue
    else:
        continue

Thanks in advance. regards, Sundaresh

Sundaresh
  • 43
  • 5
  • Have you thought about using a Dictionary? This would be a great use for a case/switch statement, which Python has no need for. I would try it with a dictionary. – mikeg Nov 26 '18 at 21:53
  • @Sufiyan Ghori - thank you for alerting me to the duplicate - the any() answers my question and provides a nifty manner. – Sundaresh Nov 26 '18 at 22:03

1 Answers1

-1

I think what you are doing is fine. The only change I would suggest is stylistic, to make sure the purpose of your for loop is not multiple indentations deep. Also, the else part is not necessary in this particular case.

#Iterate over files
for filename in os.listdir(os.getcwd()+dataDir):
    #iterate over ext (want to avoid)
    for u not in ['jpg','txt']:
        continue
    if not filename.endswith(u):
        continue
    print("An ext of my choice found!")
SMir
  • 650
  • 1
  • 7
  • 19
  • Thank you, I feel the any() function (in another note) answers my question, but your suggestion on keeping the number of indentations to a minimum is appreciated. – Sundaresh Nov 26 '18 at 22:01