Python 業務自動化 | ファイル・フォルダ自動化:基本操作 - ファイル検索

Python Python
スポンサーリンク

ファイル検索は「必要なファイルだけを正確に見つける」ための自動化の基礎

業務自動化では、フォルダの中から「条件に合うファイルだけ」を探し出す処理が非常に多く登場します。
「特定の拡張子だけ探したい」「名前に特定の文字列を含むファイルだけ処理したい」「サブフォルダも含めて検索したい」など、手作業では時間がかかる作業を Python なら一瞬で実現できます。

ここでは、初心者でも理解しやすいように、基本 → 応用 → 実務テンプレート の順で丁寧に解説します。


ファイル検索の基本:os.listdir と条件分岐

フォルダ直下のファイルを検索する基本形

まずは「フォルダ直下のファイルを検索する」最小構成です。

import os

folder = "data"

for name in os.listdir(folder):
    path = os.path.join(folder, name)

    if os.path.isfile(path):
        print("見つかったファイル:", path)
Python

ここで押さえるべき重要ポイントは次の2つです。

  • os.listdir() は「ファイル+フォルダ」をすべて返す
  • os.path.isfile() で「ファイルだけ」に絞り込む

この2ステップが、すべてのファイル検索の基礎になります。


条件検索の基本:名前・拡張子・部分一致で探す

拡張子で検索する

import os

folder = "data"

for name in os.listdir(folder):
    path = os.path.join(folder, name)

    if os.path.isfile(path) and name.lower().endswith(".csv"):
        print("CSVファイル:", path)
Python

endswith() を使うことで、拡張子検索が簡単にできます。
lower() を使うことで .CSV のような大文字にも対応できます。

名前の部分一致で検索する

import os

folder = "data"

for name in os.listdir(folder):
    path = os.path.join(folder, name)

    if os.path.isfile(path) and "report" in name.lower():
        print("report を含むファイル:", path)
Python

部分一致は「特定のキーワードを含むファイルだけ処理したい」場面で非常に便利です。


サブフォルダも含めて検索する:os.walk の活用

os.walk は「再帰的にすべての階層を探索する」

サブフォルダも含めて検索したい場合は os.walk() を使います。

import os

root = "data"

for current, dirs, files in os.walk(root):
    for name in files:
        path = os.path.join(current, name)
        print("見つかったファイル:", path)
Python

os.walk()

  • 今いるフォルダ
  • その中のフォルダ一覧
  • その中のファイル一覧
    を順番に返してくれる強力な関数です。

条件付きで検索する例

import os

root = "data"

for current, dirs, files in os.walk(root):
    for name in files:
        if name.lower().endswith(".xlsx"):
            path = os.path.join(current, name)
            print("Excelファイル:", path)
Python

サブフォルダを含めた検索は、実務で非常に役立ちます。


例題①:最新の CSV ファイルだけを検索する

シナリオ

inbox フォルダに複数の CSV があり、「最新の1つだけ」を処理したい。

コード例

import os

folder = "inbox"

latest_path = None
latest_ts = None

for name in os.listdir(folder):
    path = os.path.join(folder, name)

    if not os.path.isfile(path) or not name.lower().endswith(".csv"):
        continue

    ts = os.path.getmtime(path)

    if latest_ts is None or ts > latest_ts:
        latest_ts = ts
        latest_path = path

print("最新のCSV:", latest_path)
Python

深掘りポイント

  • 「検索 → 条件絞り込み → 更新日時で比較」という流れが重要
  • 最新ファイルだけ処理したい業務で非常に使える

例題②:特定の文字列を含むファイルをすべて検索して別フォルダへ移動

シナリオ

ファイル名に「error」を含むファイルだけを error_logs に移動したい。

コード例

import os
import shutil

src = "logs"
dst = "error_logs"

os.makedirs(dst, exist_ok=True)

for name in os.listdir(src):
    path = os.path.join(src, name)

    if os.path.isfile(path) and "error" in name.lower():
        new_path = os.path.join(dst, name)
        shutil.move(path, new_path)
        print("移動:", path, "→", new_path)
Python

深掘りポイント

  • 検索と移動を組み合わせると「自動仕分け」が実現できる
  • ログ管理・ETL処理でよく使われるパターン

例題③:サブフォルダを含めて「特定の拡張子だけ」検索して一覧化

シナリオ

project フォルダ全体から .json ファイルだけを探したい。

コード例

import os

root = "project"
results = []

for current, dirs, files in os.walk(root):
    for name in files:
        if name.lower().endswith(".json"):
            path = os.path.join(current, name)
            results.append(path)

for r in results:
    print(r)
Python

深掘りポイント

  • os.walk を使うと「階層構造を意識せずに検索できる」
  • 大規模プロジェクトのファイル管理に非常に便利

pathlib を使った、よりモダンで読みやすい検索

glob パターンで検索する

from pathlib import Path

root = Path("data")

for p in root.rglob("*.csv"):
    print("CSV:", p)
Python

rglob("*.csv") は「サブフォルダも含めて *.csv を検索する」という意味です。
直感的で読みやすく、実務でもよく使われます。


ファイル検索を安全に行うための考え方

  • ファイルかフォルダかを必ず判定する
  • 大文字小文字の揺れを吸収するために lower() を使う
  • サブフォルダを含めるかどうかで listdirwalk を使い分ける
  • 検索結果が多い場合はリストに保存して後で処理する
  • 検索条件は「拡張子」「部分一致」「更新日時」など複数組み合わせられる

ファイル検索は、業務自動化のあらゆる処理の入口になります。

タイトルとURLをコピーしました