Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use endswith with multiple extensions

Tags:

python

file

list

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
like image 250
Guillaume Avatar asked Apr 02 '14 13:04

Guillaume


People also ask

Does string end with Python?

Description. Python string method endswith() returns True if the string ends with the specified suffix, otherwise return False optionally restricting the matching with the given indices start and end.


2 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.

like image 164
Sukrit Kalra Avatar answered Oct 04 '22 05:10

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")
like image 29
Patrick Avatar answered Oct 04 '22 04:10

Patrick