【问题标题】:Use endswith with multiple extensions使用带有多个扩展名的 endwith
【发布时间】:2014-05-13 19:33:31
【问题描述】:

我正在尝试检测带有扩展名列表的文件。

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

【问题讨论】:

  • file.endswith("") 始终是True,所以你的elif 可能没有t do what you think. "。" not in file` 可能更接近。
  • 是的,应该是一个文件夹。然后我必须进入这个文件夹来获取文件。 (我已将问题编辑得更明确)
  • 您可以使用os.path.splitext(filename) 将扩展名从filename 中取出:docs.python.org/2/library/os.path.html#os.path.splitext
  • 我发现了这个:elif os.path.isdir(file) == True:

标签: python list file


【解决方案1】:

为它使用一个元组。

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

不是每次都转换,只需将其转换为元组一次。

【讨论】:

    【解决方案2】:

    你不能一开始就把它变成一个元组吗?为什么必须这样做:

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

    你就不能这样做吗:

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

    【讨论】:

    • "ext" 应该是一个类似于接受答案的列表。
    猜你喜欢
    • 2016-06-01
    • 1970-01-01
    • 2016-11-26
    • 1970-01-01
    • 2013-11-25
    • 1970-01-01
    • 1970-01-01
    • 2020-07-20
    相关资源
    最近更新 更多