Use endswith with multiple extensions

Question:

I’m trying to detect files with a list of extensions.

ext = [".3g2", ".3gp", ".asf", ".asx", ".avi", ".flv", 
                        ".m2ts", ".mkv", ".mov", ".mp4", ".mpg", ".mpeg", 
                        ".rm", ".swf", ".vob", ".wmv"]
if file.endswith(ext): # how to use the list ?
   command 1
elif file.endswith(""): # it should be a folder
   command 2
elif file.endswith(".other"): # not a video, not a folder
   command 3
Asked By: Guillaume

||

Answers:

Use a tuple for it.

>>> ext = [".3g2", ".3gp", ".asf", ".asx", ".avi", ".flv", 
                        ".m2ts", ".mkv", ".mov", ".mp4", ".mpg", ".mpeg", 
                        ".rm", ".swf", ".vob", ".wmv"]

>>> ".wmv".endswith(tuple(ext))
True
>>> ".rand".endswith(tuple(ext))
False

Instead of converting everytime, just convert it to tuple once.

Answered By: Sukrit Kalra

Couldn’t you have just made it a tuple in the first place? Why do you have to do:

>>> ".wmv".endswith(tuple(ext))

Couldn’t you just do:

>>> ext = (".3g2", ".3gp", ".asf", ".asx", ".avi", ".flv", 
                        ".m2ts", ".mkv", ".mov", ".mp4", ".mpg", ".mpeg", 
                        ".rm", ".swf", ".vob", ".wmv")
Answered By: Patrick
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.