Pythonでディレクトリ走査するときに深さを指定するのはこうすれば良い!

はてなブックマーク - Pythonでディレクトリ走査するときに深さを指定するのはこうすれば良い!
LINEで送る
Pocket

Pythonでプログラミングするときに

こんな課題がありました!

directoryスキャンするときに深さを指定したい!

こんなとき、下記の関数を使うと簡単にできます!

各行の処理の意味をインラインでコメントを書いておきますので

ご参考ください!

find_all_files(directory)

#
# 関数を定義する
#
def find_all_files(directory):
    # スキャンする対象directoryを'/'以降をとる
    dir_string = directory.rstrip(os.path.sep)
    # 属性がdirectoryでなければ、一回エラーを出す(条件式がTrueではない時に、例外を投げます。)
    assert os.path.isdir(dir_string)
    # スキャンする対象directoryは何階層かを調べておく、つまり'/'の数を数える
    directory_depth = dir_string.count(os.path.sep)
    # 遍歴していく
    for root, dirs, files in os.walk(directory):
        # 今の深さを計算する、つまり'/'を数える
        current_depth = root.count(os.path.sep)
        # もし、今の深さ>=(スキャンする対象directory +スキャンしたい深さ) 
        if current_depth >= directory_depth + int(your_check_scan_depth):
            # 何もしないスキップする
            print('スキップ')
        else:
            # 一回その階層のフォルダーを出力する
            yield root
            # 続いて、その階層の下のファイルを順次出力する
            for file in files:
                # 深さは指定された深さより浅いとき、通常処理していく
                yield os.path.join(root, file)

# END

この関数を利用して後続の処理をしていけます!

find_all_files(directory)を利用する

#
# こんな感じで上の関数を利用する
#
for file in find_all_files(your_check_target_path):
    print('フォルダスキャン、見つけたファイル->',file)

ここのファイルは

Python の

ファイルオブジェクトです。

まとめ

いかがですか?

今回の記事はとてもシンプルな内容ですが

いざやろうとするときに、なかなか躊躇したりすることもありますよね

上の内容を皆さんのご参考になれば嬉しいです。

では、また!

はてなブックマーク - Pythonでディレクトリ走査するときに深さを指定するのはこうすれば良い!
LINEで送る
Pocket

Add a Comment

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close