Python - 循环遍历某些扩展名的文件 [英] Python - Loop through files of certain extensions

查看:85
本文介绍了Python - 循环遍历某些扩展名的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遍历文件夹和所有子文件夹以查找特定文件类型的所有文件 - 例如,只有 .mp4、.avi、.wmv.

I'm trying to loop through a folder and all subfolders to find all files of certain file types - for example, only .mp4, .avi, .wmv.

这是我现在拥有的,它遍历所有文件类型:

Here is what I have now, it loops through all file types:

import os
rootdir = 'input'

for subdir, dirs, files in os.walk(rootdir):
     for file in files:
          print (os.path.join(subdir, file))

谢谢!

推荐答案

你可以使用 os.path.splitext 它接受一个路径并从它的末尾分割文件扩展名:

You can use os.path.splitext which takes a path and splits the file extension from the end of it:

import os
rootdir = 'input'
extensions = ('.mp4', '.avi', '.wmv')

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        ext = os.path.splitext(file)[-1].lower()
        if ext in extensions:
            print (os.path.join(subdir, file))

这篇关于Python - 循环遍历某些扩展名的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆