python怎么读取所有文件夹里的视频
时间: 2024-09-24 22:14:34 浏览: 46
pythonpython代码实现多张图片合成视频方法.rar
在Python中,你可以使用os模块来遍历目录及其子目录,并结合如`cv2`(计算机视觉库)或`moviepy`等库来读取视频文件。下面是一个基本的示例,展示如何使用os和`cv2.VideoCapture`来读取指定路径下的所有视频:
```python
import os
import cv2
def read_videos_in_dir(directory):
video_files = []
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith(('.mp4', '.avi', '.mkv')): # 添加你关心的视频文件格式
video_path = os.path.join(root, file)
try:
cap = cv2.VideoCapture(video_path) # 尝试打开视频
if cap.isOpened():
video_files.append(video_path)
print(f"Found video: {video_path}")
else:
print(f"Failed to open video: {video_path}")
except Exception as e:
print(f"Error reading video {file}: {e}")
continue
return video_files
directory_to_search = 'your_directory_path' # 替换为你想要搜索的目录路径
videos = read_videos_in_dir(directory_to_search)
阅读全文