LoginSignup
53
51

More than 5 years have passed since last update.

pythonで任意のディレクトリ以下の全てのファイルを処理する(追記あり)

Last updated at Posted at 2017-12-07

はじめに

pythonを使ってあるディレクトリ以下の全てのファイルを処理することがあったので、その方法をまとめます。

全てのファイルにアクセスする方法

基本的には、ディレクトリを探索して中のファイルを調べて、ファイルだったら処理、ディレクトリだったらさらに探索、というのを再帰的に繰り返します。

import os
ROOT_PATH = 'ルートディレクトリ'


def prcess(file_path):
    # 処理を記述


def recursive_file_check(path):
    if os.path.isdir(path):
        # directoryだったら中のファイルに対して再帰的にこの関数を実行
        files = os.listdir(path)
        for file in files:
            recursive_file_check(path + "\\" + file)
    else:
        # fileだったら処理
        process(path)


recursive_file_check(ROOT_PATH)

特定のファイル形式のファイルのみ処理したいとき

else:ブロックを通過するときにif文でfilterを通してあげれば実装できます。後ろの文字から拡張子をするのが楽だと思います。

例えばエクセル形式のファイルのみを処理したいときは、

    else:
        if path[-4:] == '.xls' or path[-5:] == '.xlsx':
            process(path)

などとすれば、エクセルファイルだったときのみ処理をすることができます。

追記

わざわざ再帰検索をせずとも、ディレクトリ下の全てを出してくれる関数os.walkを使うともっと楽にかけます。

def file_check(path):
    for pathname, dirnames, filenames in os.walk(path):
        for filename in filenames:
             process(os.path.join(pathname,filename)

とてもすっきりしました!

フィルターに関しても、endswith関数を使えばわざわざスライスせずとも簡単に調べることができます。上と同様の例は、次のようになります。

def simple_check(path):
    for pathname, dirnames, filenames in os.walk(path):
        for filename in filenames:
             # フィルタ処理
             if filename.endswith('.xls') or filename.endswith('.xlsx'):
                    check(os.path.join(pathname,filename)
53
51
4

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
53
51