LoginSignup
1
1

More than 5 years have passed since last update.

特定の拡張子を持つすべてのファイルをジェネレート

Last updated at Posted at 2015-10-26

指定ディレクトリ以下のすべてのファイルをなめて、希望の拡張子を持つファイルのファイルパスのみをジェネレータ的に返す。os.walk を使うとできる。

よく使う操作だとは思いつつすぐ書き方を忘れるのでメモも兼ねて今後のために関数化しておく。Python2系でも3系でも使える。

import os


def walk_files_with(extension, directory='.'):
    """Generate paths of all files that has specific extension in a directory. 

    Arguments:
    extension -- [str] File extension without dot to find out
    directory -- [str] Path to target directory

    Return:
    filepath -- [str] Path to file found
    """
    for root, dirnames, filenames in os.walk(directory):
        for filename in filenames:
            if filename.lower().endswith('.' + extension):
                yield os.path.join(root, filename)

実際にはこんな感じで使う。

for filepath in walk_files_with('csv', './data/'):
    print(filepath)

Python 3.4 以上なら pathlib 使ったほうがスマートかもねー。

1
1
0

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