首页 > 解决方案 > Python递归查找具有特定扩展名的文件

问题描述

我正在尝试查找目录中的所有电影文件。修改了在 SO 上找到的一些代码,但它只找到 12 个电影文件,而实际上目录中总共有 17 个 .mp4s 和 .movs ......最终,我试图截取每个视频文件的屏幕截图间隔,并且当我获得高清素材时,可以快速生成“联系表”。

import os
import pandas as pd

folder_to_search = 'C:\\Users\\uname\\Desktop\\footage-directory'

extensions = ('.avi', '.mkv', '.wmv', '.mp4', '.mpg', '.mpeg', '.mov', '.m4v')


def findExt(folder):
    matches = []
    return [os.path.join(r, fn)
        for r, ds, fs in os.walk(folder) 
        for fn in fs if fn.endswith(extensions)]

print(len(findExt(folder_to_search)))
>>returns 12

在此处输入图像描述

标签: pythonvideo

解决方案


>>> 'venom_trailer.Mp4'.endswith('mp4') # <-- file having .Mp4 extension is still a valid video file so it should have been counted. 
False

>>> 'venom_trailer.Mp4'.lower().endswith('mp4')
True

#------------
>>> file_name = 'venom_trailer.Mp4'
>>> last_occurance_of_period = file_name.rfind('.')
>>> file_extension = file_name[last_occurance_of_period:]
>>> file_extension
'.Mp4'
>>> file_extension.lower() == '.mp4'
True
#------------

# replace this line 
for fn in fs if fn.endswith(extensions) 
# with this
for fn in fs if fn.lower().endswith(extensions) 
# or with this
for fn in fs if fn[fn.rfind('.'):].lower() in extensions]

推荐阅读