LoginSignup
5
4

More than 5 years have passed since last update.

指定の拡張子のファイルを探索する

Last updated at Posted at 2017-02-26

カレントディレクトリのみ

import os
import glob


def find_all_files_with_ext(ext):
    pattarn = '*' + os.extsep + ext
    return glob.glob(pattarn)

サブディレクトリも含む

import os


def _find_all_files_with_ext(dir, ext):
    suffix = os.extsep + ext.lower()
    for root, dirs, files in os.walk(dir):
        for file in files:
            if file.lower().endswith(suffix):
                yield os.path.join(root, file)


def find_all_files_with_ext(dir, ext):
    return list(_find_all_files_with_ext(dir, ext))

※ 上のメソッドを先に書いたのでメソッドを分けた状態で載せてますが、リストで取得するだけなら、メソッドを分ける必要は特にないです。
※ インデックス指定比較と比べて、可読性が良く同程度のパフォーマンスであったので、endswith メソッドに修正。

参考資料

5
4
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4