Python递归查找具有特定扩展名的文件

时间:2018-09-29 00:13:01

标签: python video

我正在尝试查找目录中的所有电影文件。修改了some code found on SO,但是它只能找到12个电影文件,而实际上目录中总共有17个.mp4和.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

enter image description here

1 个答案:

答案 0 :(得分:1)

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