Python | 正規表現を使ったファイル一括処理スクリプト

Python
スポンサーリンク

では 初心者向けに、正規表現を使ってファイルを一括処理し、ログからエラーを抽出するスクリプト を作ってみましょう。Python で動く形で、コメントも付けて詳しく解説します。


1. 前提

  • ログファイルはテキストファイル(例:log.txt
  • 各行にタイムスタンプとログレベル(INFO, WARNING, ERROR)が含まれている
  • 目的は ERROR 行だけ抽出して別ファイルに保存する

例:log.txt の中身

2025-11-05 10:00:00 INFO System start
2025-11-05 10:01:00 ERROR Failed to load module
2025-11-05 10:02:00 WARNING Low memory
2025-11-05 10:03:00 ERROR Connection timeout

2. Python スクリプト例

import re

# 入力ファイルと出力ファイル
input_file = "log.txt"
output_file = "error_log.txt"

# 正規表現パターン(ERROR を含む行)
pattern = re.compile(r"ERROR")  # 単純に ERROR が含まれる行を抽出

# 抽出した行を格納するリスト
error_lines = []

# ファイルを読み込んで処理
with open(input_file, "r", encoding="utf-8") as f:
    for line in f:
        # 正規表現でマッチしたら error_lines に追加
        if pattern.search(line):
            error_lines.append(line.strip())  # strip() で改行を削除

# 結果を出力ファイルに書き込む
with open(output_file, "w", encoding="utf-8") as f:
    for line in error_lines:
        f.write(line + "\n")

print(f"{len(error_lines)} 件のエラーを {output_file} に保存しました。")
Python

3. 解説

  1. re.compile(r"ERROR")
    • 正規表現パターンを作成。
    • r"" の生文字列で書くと \ を使う場合も安全。
  2. pattern.search(line)
    • 行のどこかに ERROR が含まれていれば True になる。
    • match() だと先頭からしか見ないので注意。
  3. line.strip()
    • 改行や余分な空白を削除して整形。
  4. with open(...) as f:
    • ファイルを安全に開く。自動で閉じてくれるので便利。
  5. 書き込みは f.write(line + "\n") で改行をつける。

4. 応用例

4-1: 日付ごとにフォルダ分け

import os
import re
from datetime import datetime

input_file = "log.txt"
pattern = re.compile(r"ERROR")

with open(input_file, "r", encoding="utf-8") as f:
    for line in f:
        if pattern.search(line):
            # 日付部分を抽出(例: 2025-11-05)
            date = line[:10]
            os.makedirs(date, exist_ok=True)
            with open(f"{date}/error_log.txt", "a", encoding="utf-8") as out_f:
                out_f.write(line)
Python
  • 日付ごとにフォルダを作って ERROR 行を保存。
  • os.makedirs(..., exist_ok=True) で既存フォルダでもエラーにならない。

4-2: 複雑な条件で抽出

  • 正規表現で時間帯やモジュール名まで指定可能:
pattern = re.compile(r"ERROR.*module")
Python
  • 「ERROR で、後ろに module を含む行」だけ抽出。

5. 練習課題(自分でやってみよう)

  1. ログから WARNING 行だけ を抽出するコードを書いてみよう。
  2. エラー行の 時間だけ抽出(例:10:01:00)してリスト化してみよう。
  3. 複数のログファイル(log1.txt, log2.txt …)をまとめて処理するバッチスクリプトを作ろう。
Python
スポンサーリンク
シェアする
@lifehackerをフォローする
スポンサーリンク
タイトルとURLをコピーしました