【问题标题】:How to loop through files of certain extensions?如何遍历某些扩展名的文件?
【发布时间】:2015-08-11 17:44:45
【问题描述】:

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

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

import os
rootdir = 'input'

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

【问题讨论】:

  • 对于通过搜索来到这里的初学者,请注意,OP 的代码通过子目录递归,并在整个目录树中查找具有特定扩展名的所有文件(文件夹中的文件夹等在起始文件夹中)。

标签: python python-3.x


【解决方案1】:

对于多个扩展,最简单的就是使用str.endswith传递一个子字符串的元组来检查:

  for file in files:
      if file.endswith((".avi",".mp4","wmv")):
         print (os.path.join(subdir, file))

您可以像下面一样使用iglob 并链接返回的搜索或使用re.search,但使用endswith 可能是最好的方法。

from itertools import chain
from glob import iglob

for subdir, dirs, files in os.walk(rootdir):
    for file in chain.from_iterable(iglob(os.path.join(rootdir,p)) for p in ("*.avi", "*.mp4", "*wmv")) :
            print(os.path.join(subdir, file))

使用 python3.5 glob 现在支持使用 ** 语法的递归搜索:

from itertools import chain
from glob import iglob

from glob import iglob
for file in chain.from_iterable(iglob(os.path.join(rootdir,p)) 
      for p in (rootdir+"**/*.avi", "**/*.mp4", "**/*wmv")):
          print(file)

【讨论】:

    【解决方案2】:

    您可以使用os.path.splitext,它采用路径并从其末尾拆分文件扩展名:

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

    【讨论】:

    • 感谢 ozgur,这段代码与我最初的代码最接近 - 也很容易理解。如果大规模完成(未测试!),其他答案可能会更有效,但对于我的简单任务,这完全足够了。
    【解决方案3】:

    几天前我实际上做了类似的事情,我是这样做的:

    EXTENSIONS = ('.cpp','.hpp')
    
    for root, dirs, files in os.walk(top):
        for file in files:
            if file.endswith(EXTENSIONS):
                #file which ends with extension type so do your thing!
    

    希望这就是你所追求的。您可以在我的github 上查看整个脚本。

    【讨论】:

      【解决方案4】:

      这一行解决方案也可能有助于获取当前目录中的所有 .py 文件

      for file in list(filter(lambda x: x.endswith('.py'), os.listdir('./'))):
          print(file) 
      

      【讨论】:

        【解决方案5】:

        从 Python 3.4 开始你可以使用pathlib:

        from pathlib import Path
        from itertools import chain
        
        rootdir = 'input'
        p = Path(rootdir)
        for file in (chain(p.glob('**/*.mp4'), p.glob('**/*.avi'))):
            print(file)
        

        【讨论】:

          猜你喜欢
          • 2011-06-06
          • 1970-01-01
          • 1970-01-01
          • 2016-09-12
          • 1970-01-01
          • 2019-05-16
          • 2021-12-28
          • 2020-09-27
          • 2016-09-02
          相关资源
          最近更新 更多